<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/dute_favicon_32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/dute_favicon_16x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <link rel="manifest" href="/images/manifest.json">
  <meta name="msapplication-config" content="/images/browserconfig.xml">
  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">
  <meta name="google-site-verification" content="mpI5dkydstZXl6UcDCppqktXK0bbvqdZ6LkZ3KNk4Iw">
  <meta name="baidu-site-verification" content="code-a1LksZX2Ds">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"whitestore.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="Spring事务机制个人总结">
<meta property="og:type" content="article">
<meta property="og:title" content="【Spring】Spring 事务机制的个人总结">
<meta property="og:url" content="https://whitestore.top/2023/07/14/spring-total/index.html">
<meta property="og:site_name" content="爱看书的阿东">
<meta property="og:description" content="Spring事务机制个人总结">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20220103215722.png">
<meta property="og:image" content="https://adong-picture.oss-cn-shenzhen.aliyuncs.com/adong/20220902105321.png">
<meta property="og:image" content="https://adong-picture.oss-cn-shenzhen.aliyuncs.com/adong/20220902105414.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211229220810.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211229220833.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211229220848.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211230171527.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211230171507.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211231151719.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20220102161325.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20220102163759.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211227223244.png">
<meta property="article:published_time" content="2023-07-14T02:44:26.000Z">
<meta property="article:modified_time" content="2023-07-16T06:28:09.255Z">
<meta property="article:author" content="阿东">
<meta property="article:tag" content="spring">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20220103215722.png">

<link rel="canonical" href="https://whitestore.top/2023/07/14/spring-total/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【Spring】Spring 事务机制的个人总结 | 爱看书的阿东</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="爱看书的阿东" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">爱看书的阿东</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">赐他一块白色石头，石头上写着新名</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/sitemap.xml" rel="section"><i class="fa fa-fw fa-sitemap"></i>站点地图</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL2xhenlUaW1lcw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://whitestore.top/2023/07/14/spring-total/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="阿东">
      <meta itemprop="description" content="随遇而安">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱看书的阿东">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【Spring】Spring 事务机制的个人总结
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2023-07-14 10:44:26" itemprop="dateCreated datePublished" datetime="2023-07-14T10:44:26+08:00">2023-07-14</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2023-07-16 14:28:09" itemprop="dateModified" datetime="2023-07-16T14:28:09+08:00">2023-07-16</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Spring/" itemprop="url" rel="index"><span itemprop="name">Spring</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2023/07/14/spring-total/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2023/07/14/spring-total/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>56k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>51 分钟</span>
            </span>
            <div class="post-description">Spring事务机制个人总结</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="【Spring】Spring-事务机制的个人总结"><a href="#【Spring】Spring-事务机制的个人总结" class="headerlink" title="【Spring】Spring 事务机制的个人总结"></a>【Spring】Spring 事务机制的个人总结</h1><h1 id="一、引言"><a href="#一、引言" class="headerlink" title="一、引言"></a>一、引言</h1><p>​    Spring的事务机制虽然已经有非常多的资料介绍了，但是实际使用的时候还是常常栽坑里，相信这是大部分程序员的目前或者曾经的使用感受，所以这篇文章将会做一个完整的总结，用理论结合实际的代码实战的方式来弄懂Spring事务的机制到底应该如何使用以及内部是如何进行设计的。</p>
<p>​    在介绍正文之前，希望这篇教程不单单是能让读者避开Spring事务的陷阱，更多的是希望能够从Spring的事务设计上锻炼自己的架构思维，如果你一开始完全不懂，可以像我一样进行一比一复刻用在<strong>自己的开源工具或者项目上</strong>，不要管为什么这么设计，只管模仿再去思考，多想想自己用起来有什么便利性，然后再反推思考。</p>
<p>​    另外如果你完全不懂JDBC或者数据库的话，这篇文章可能就不太适合你看了，笔者也并不想浪费读者时间，可以看看下面这本老外写的JDBC入门文档，粗略翻了一下发现还是挺适合新手的，顺带磨练下英语阅读水平（实在不行还有谷歌娘兜底不是）：</p>
<blockquote>
<p>《jdbc》（简单粗暴的名字）</p>
<p>链接：<span class="exturl" data-url="aHR0cHM6Ly9wYW4uYmFpZHUuY29tL3MvMUNPVmlzeTlEeUpSNXVqOWhzQjRXb1E=" title="https://pan.baidu.com/s/1COVisy9DyJR5uj9hsB4WoQ">https://pan.baidu.com/s/1COVisy9DyJR5uj9hsB4WoQ<i class="fa fa-external-link"></i></span><br>提取码：x5tz<br>–来自百度网盘超级会员V7的分享</p>
</blockquote>
<p>如果觉得文章写得不错，欢迎点赞收藏支持一波。</p>
<a id="more"></a>

<h2 id="最好的资料"><a href="#最好的资料" class="headerlink" title="最好的资料"></a>最好的资料</h2><p>​    最好的博客永远是官方文档，建议了解Spring事务事务之前多读几遍：（版本 5.3.14）</p>
<p><span class="exturl" data-url="aHR0cHM6Ly9kb2NzLnNwcmluZy5pby9zcHJpbmctZnJhbWV3b3JrL2RvY3MvY3VycmVudC9yZWZlcmVuY2UvaHRtbC9kYXRhLWFjY2Vzcy5odG1sI3NwcmluZy1kYXRhLXRpZXI=" title="https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#spring-data-tier">https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#spring-data-tier<i class="fa fa-external-link"></i></span></p>
<p>​    另外官方文档在事务这一节的最后推荐了两个扩展资料，这里也一并推荐：</p>
<blockquote>
<p>有关 Spring Framework 的事务支持的更多信息，请参阅：</p>
<p><strong><span class="exturl" data-url="aHR0cHM6Ly93d3cuaW5mb3dvcmxkLmNvbS9hcnRpY2xlLzIwNzc5NjMvZGlzdHJpYnV0ZWQtdHJhbnNhY3Rpb25zLWluLXNwcmluZy0td2l0aC1hbmQtd2l0aG91dC14YS5odG1s" title="https://www.infoworld.com/article/2077963/distributed-transactions-in-spring--with-and-without-xa.html">Spring 中的分布式事务<i class="fa fa-external-link"></i></span></strong>：分布式事务极具影响力的一篇文章，也是了解分布式事务一篇必读文，带和不带 XA 的一个 JavaWorld 演示，其中 Spring 的 <code>David Syer</code> 将指导您了解 Spring 应用程序中分布式事务的七种模式，其中三种带 XA，其他四种不带。</p>
<p>这里还找到一篇翻译：<a href="https://github.com/wangfeishsh/baocy/blob/master/distributed-transactions-in-spring-with-and-without-xa.md" target="_blank" rel="noopener"><strong>distributed-transactions-in-spring-with-and-without-xa.md</strong></a></p>
<p><strong>Java Transaction Design Strategies</strong> 是 InfoQ 提供的一本书，它对 Java 中的事务提供了节奏明快的介绍。 它还包含有关如何通过 Spring Framework 和 EJB3 配置和使用事务的并行示例。</p>
<p>书籍资源链接: <span class="exturl" data-url="aHR0cHM6Ly9wYW4uYmFpZHUuY29tL3MvMVoxVmRUWnhPOUxMcm9sWHhLTGEzTEE=" title="https://pan.baidu.com/s/1Z1VdTZxO9LLrolXxKLa3LA">https://pan.baidu.com/s/1Z1VdTZxO9LLrolXxKLa3LA<i class="fa fa-external-link"></i></span> 提取码: hads </p>
</blockquote>
<h1 id="二、事务介绍"><a href="#二、事务介绍" class="headerlink" title="二、事务介绍"></a>二、事务介绍</h1><p>首先我们需要大致了解什么是事务，一句话概括就是：<strong>一组操作要么全部一起执行，要么全部的不执行</strong>。</p>
<h2 id="（1）事务特性（ACID-）"><a href="#（1）事务特性（ACID-）" class="headerlink" title="（1）事务特性（ACID ）"></a>（1）事务特性（ACID ）</h2><p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20220103215722.png" alt=""></p>
<p>​    事务通常有下面的四种特性：</p>
<ul>
<li><strong>一致性</strong>：一致性保证事务的操作前后数据都正确的。</li>
<li><strong>原子性</strong>：事务是操作的最小单位，每一个事务要么全部成功，要么全部失败。</li>
<li><strong>隔离性</strong>：隔离性需要保证不同的事务之间不会互相干扰。</li>
<li><strong>持久性</strong>：事务提交之后数据将会永久生效并且保存。</li>
</ul>
<p>​    这四种特性虽然简单但是真要记住确实有些难，为了方便记忆我们用一些案例进行联想记忆，也可以按照自己容易记忆的方式联想记忆：</p>
<blockquote>
<p>​    首先，数据需要保证操作前的结果和操作后的结果一致，比如银行卡余额有1000元要往银行卡充值2000，充值完成之后我们看到的数据就是3000否则就还是1000元，所以<strong>一致性</strong>是首先需要保证的。</p>
<p>然后假设此时余额还是1000元，此时扣除500元，充值1000元，如果成功最后余额一定是1500元，需要保证两个操作同时完成，要么同时不完成，这就是<strong>原子性</strong>，原子性可以看做是保证多次连续操作的一致。</p>
<p>接下来是<strong>隔离性</strong>，隔离性比较好理解，你在ATM机器操作的时候如果进行充值，这中间的所有数据都是只有你可以见的，1000块钱存进去看到的结果一定是2000块钱而不是最后变成500块钱（不然这你绝对要报警了）。</p>
<p>最后事务一定是需要保证安全的，所以所有的事务只要成功就能<strong>永久生效</strong>，不受突然断电任何情况的影响，但是持久性依赖具体数据库的实现，当这是多数数据库的主要保证。</p>
</blockquote>
<h2 id="（2）并发事务的存在的问题"><a href="#（2）并发事务的存在的问题" class="headerlink" title="（2）并发事务的存在的问题"></a>（2）并发事务的存在的问题</h2><p>​    并发事务存在几个常见的问题，那就是<strong>脏读，不可重复读，幻读</strong>，<strong>丢失回滚（第一类事务丢失），丢失修改（第二类事务丢失）</strong>，这里需要小心区分<strong>不可重复读</strong>和<strong>幻读</strong>这两种情况差异。</p>
<p>​    1. <strong>脏读</strong>：最简单的话理解就是读到了其他事务没有提交的数据，也就是读到了未提交的数据，所以这个数据不管是否正确，其执行结果可能是不正确。</p>
<p>​    2. <strong>不可重复读</strong>：不可重复读针对当前事务读取到其他事务修改或者删除的数据，比如当前事务之前读取数据行为20，但是后一次读取却变成了30，数据和之前不重复了，所以就是不可重复读，但是需要注意不可重复读并不是一个十分严重的问题，这取决于数据库所以这也是为什么有不少数据库不设置默认级别为这个级别其中一个原因。</p>
<ol start="3">
<li><strong>幻读</strong>：幻读和不可重复读最大的区别是读到了其他事务提交的<strong>新增</strong>数据，就好像当前事务读取数据出现了幻觉，之前读取出来的值和后一次读出来的值的内容不一致。</li>
<li><strong>丢失修改</strong>（第二类事务丢失）：有一种情况丢失修改，丢失修改指的是两个事务同时提交事务覆盖同一份数据的情况，不管事务A成功还是事务B成功，最后总会有一方修改的数据是失效的。</li>
<li><strong>丢失回滚</strong>（第一类事务丢失）：丢失回滚指A事务提交了，但是B事务事务回滚了，当A提交成功但是B因为回滚事务回滚了A的数据，这时候对于A来说事务就算是丢失了。</li>
</ol>
<h2 id="（3）事务的隔离级别"><a href="#（3）事务的隔离级别" class="headerlink" title="（3）事务的隔离级别"></a>（3）事务的隔离级别</h2><p>​    事务的隔离级别就是来解决并发事务问题的，需要注意的是下面介绍的内容并不是所有的数据库都支持（也可能支持但是只支持一部分），如果无特殊说明默认为Mysql。</p>
<ul>
<li><strong>READ UNCOMMITTED（读未提交）</strong>：对应脏读的模式，会读到其他事务没有提交的数据，几乎无数据安全和可靠性的保证。</li>
<li><strong>READ COMMITTED（读已提交）</strong>：事务会读取已提交的数据，也是大多数数据库的默认隔离级别。但是读到已提交的数据存在读到其他事务提交的新增数据的情况，所以会存在可重复读的情况。</li>
<li><strong>PEPEATABLE READ（可重复读）</strong>：这个级别是MySQL的默认隔离级别，它解决了脏读的问题，同时也保证了同一个事务多次读取同样的记录是一致的，但这个级别还是会出现幻读的情况。幻读是指当一个事务A读取某一个范围的数据时，另一个事务B在这个范围插入行，A事务再次读取这个范围的数据时，会产生幻行。特别说明：<strong>InnoDB和XtraDB存储引擎通过多版本并发控制（MVCC，Multiversion Concurrency Control）解决了幻读问题，它使用间隙锁（next-key locking）锁定查询涉及的行和索引中的间隙，防止幻影行的插入</strong>。</li>
<li><strong>SERIALIZABLE（可串行化）</strong>：这个事务是最高的隔离级别，它强制事务串行执行，避免了幻读问题。简单来说，SERIALIZABLE会在读取的每一行数据上都加锁，所以可能会导致大量的超时和锁竞争</li>
</ul>
<h2 id="（4）设置和回滚到保存点"><a href="#（4）设置和回滚到保存点" class="headerlink" title="（4）设置和回滚到保存点"></a>（4）设置和回滚到保存点</h2><p>​    注意保存点和事务的隔离级别一样，依赖于具体的数据库是否支持。保存点使用方式是在当前事务中通过<code>Connection.setSavepoint</code>设置一个<code>Savepoint</code>对象，利用<code>Connection.rollback</code>方法进行回滚，同时接受一个<code>Savepoint</code>参数。可以理解为一个存档，存档之后，可以回滚到指定存档点，这里用一个网上的sql案例简单理解，下面的案例重点关注：<code>ROLLBACK TO SAVEPOINT s1;</code>和<code>SAVEPOINT s1;</code>和<code>SAVEPOINT s2;</code>这几条语句：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">回滚事务到保存点。</span><br><span class="line"></span><br><span class="line"><span class="comment">--删除表bonus_2017。</span></span><br><span class="line"><span class="keyword">DROP</span> <span class="keyword">TABLE</span> <span class="keyword">IF</span> <span class="keyword">EXISTS</span> bonus_2017;</span><br><span class="line"><span class="comment">--创建表bonus_2017。</span></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> bonus_2017(staff_id <span class="built_in">INT</span> <span class="keyword">NOT</span> <span class="literal">NULL</span>, staff_name <span class="built_in">CHAR</span>(<span class="number">50</span>), job <span class="built_in">VARCHAR</span>(<span class="number">30</span>), bonus <span class="built_in">NUMBER</span>);</span><br><span class="line"><span class="comment">--向表bonus_2017中insert记录1。</span></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> bonus_2017(staff_id, staff_name, job, bonus) <span class="keyword">VALUES</span>(<span class="number">23</span>,<span class="string">'limingwang'</span>,<span class="string">'developer'</span>,<span class="number">5000</span>);</span><br><span class="line"><span class="comment">--提交事务。</span></span><br><span class="line"><span class="keyword">COMMIT</span>;</span><br><span class="line"><span class="comment">--设置保存点s1。</span></span><br><span class="line"><span class="keyword">SAVEPOINT</span> s1;</span><br><span class="line"><span class="comment">--向表bonus_2017中insert记录2。</span></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> bonus_2017(staff_id, staff_name, job, bonus) <span class="keyword">VALUES</span>(<span class="number">24</span>,<span class="string">'liyuyu'</span>,<span class="string">'tester'</span>,<span class="number">7000</span>);</span><br><span class="line"><span class="comment">--设置保存点s2。</span></span><br><span class="line"><span class="keyword">SAVEPOINT</span> s2;</span><br><span class="line"><span class="comment">--查询表bonus_2017的数据。</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">FROM</span> bonus_2017;</span><br><span class="line"></span><br><span class="line">STAFF_ID     STAFF_NAME                                         JOB                            BONUS           </span><br><span class="line"><span class="comment">------------ -------------------------------------------------- ------------------------------ ----------------------------------------</span></span><br><span class="line">23           limingwang                                          developer                         5000                 </span><br><span class="line">24           liyuyu                                              tester                        7000                 </span><br><span class="line"></span><br><span class="line">2 rows fetched.</span><br><span class="line"><span class="comment">--回滚到保存点s1。</span></span><br><span class="line"><span class="keyword">ROLLBACK</span> <span class="keyword">TO</span> <span class="keyword">SAVEPOINT</span> s1;</span><br><span class="line"><span class="comment">--查询表bouns_2017的数据。</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">FROM</span> bonus_2017;</span><br><span class="line"></span><br><span class="line">STAFF_ID     STAFF_NAME                                         JOB                            BONUS           </span><br><span class="line"><span class="comment">------------ -------------------------------------------------- ------------------------------ ----------------------------------------</span></span><br><span class="line">23           limingwang                                          developer                         5000                 </span><br><span class="line"></span><br><span class="line">1 rows fetched.</span><br></pre></td></tr></table></figure>



<h1 id="三、Spring事务介绍"><a href="#三、Spring事务介绍" class="headerlink" title="三、Spring事务介绍"></a>三、Spring事务介绍</h1><h2 id="（1）Spring事务是啥？"><a href="#（1）Spring事务是啥？" class="headerlink" title="（1）Spring事务是啥？"></a>（1）Spring事务是啥？</h2><p>​    Spring的事务可以看做是在spring对于不同数据库的操作细节的一种封装和掩盖，通过三个核心的组件来完成整个事务的控制，这三个组件分别是：</p>
<ul>
<li><strong>PlatformTransactionManager：</strong> （平台）事务管理器</li>
<li><strong>TransactionDefinition：</strong> 事务定义信息(事务隔离级别、传播行为、超时、只读、回滚规则)</li>
<li><strong>TransactionStatus：</strong> 事务运行状态</li>
</ul>
<p>​    spring事务在进行操作的时候通过自定义了七种不同的事务等级来完成事务提交回滚等一系列的操作，这里先卖个关子。</p>
<h2 id="（2）事务设计"><a href="#（2）事务设计" class="headerlink" title="（2）事务设计"></a>（2）事务设计</h2><p>​    我们稍微扩展介绍一下上面三个组件的内容：</p>
<ul>
<li><strong>PlatformTransactionManager：</strong> （平台）事务管理器，定义了事务的通用接口，最主要的实现抽象类为：AbstractPlatformTransactionManager，如前面所说，他定了事务操作的模板方法，由子类实现具体的事务细节，比如回滚，提交事务，设置参数等操作。</li>
<li><strong>TransactionDefinition：</strong> 事务定义信息，可以看作是一个事连接务的属性和配置，事务属性分为下面五种：<ul>
<li><strong>事务隔离级别</strong>：事务隔离几倍并不是所有的数据库都支持，并且部分数据库由于存储引擎的不同也可能不支持。</li>
<li><strong>传播行为</strong>：传播行为有七种，默认级别为：<strong>PROPAGATION_REQUIRED</strong>。</li>
<li><strong>事务超时</strong>：指一个事务所允许执行的最长时间，如果超过该时间限制但事务还没有完成，则自动回滚事务。</li>
<li><strong>回滚规则</strong>：规定了当前的事务会在什么情况下进行回滚，默认情况是按照运行时异常进行回滚，也可以设置指定某些异常不进行回滚，但是需要注意指定异常类必须是Throwable的子类。</li>
<li><strong>是否只读</strong>：事务的只读属性是指对事务性资源进行只读操作或者是读写操作</li>
</ul>
</li>
<li><strong>TransactionStatus：</strong> 事务运行状态，可以看做是一个新的事务对象，此接口包含了下面的内容</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">TransactionStatus</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isNewTransaction</span><span class="params">()</span></span>; <span class="comment">// 是否是新的事物</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">hasSavepoint</span><span class="params">()</span></span>; <span class="comment">// 是否有恢复点</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">setRollbackOnly</span><span class="params">()</span></span>;  <span class="comment">// 设置为只回滚</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isRollbackOnly</span><span class="params">()</span></span>; <span class="comment">// 是否为只回滚</span></span><br><span class="line">    <span class="keyword">boolean</span> isCompleted; <span class="comment">// 是否已完成</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="（3）实现形式"><a href="#（3）实现形式" class="headerlink" title="（3）实现形式"></a>（3）实现形式</h2><p>​    Spring事务有两种实现形式，关于实现形式将会在后文进行详细的讲解：</p>
<ol>
<li><strong>编程式模式</strong>：硬编码，也可以称之为手动模式，其实可以看作对于jdbc做了一层封装，一般使用 <strong>TransactionTemplate</strong> 模板对象进行事务的相关操作。</li>
<li><strong>声明式模式</strong>：特点是使用<strong>@Transactional</strong> 注解完成切面的事务注入。其底层使用的是aop和动态代理。</li>
</ol>
<blockquote>
<p>spring的事务是对于aop和动态代理的设计模式的教科书实现，如果对于Spring源代码比较棘手的可以从Spring的事务开始了解，如果看不懂那就需要补补aop和动态代理的功课了。</p>
</blockquote>
<p>下面我们分别来看看编程式事务和声明式事务的实现方式。</p>
<h2 id="（4）事务的传播级别"><a href="#（4）事务的传播级别" class="headerlink" title="（4）事务的传播级别"></a>（4）事务的传播级别</h2><p>​    Spring的事务传播级别主要是下面的七种，关于事务传播的部分细节会在声明式事务的“理解事务传播级别”介绍，同时实战部分会通过一些简单的案例来看一下不同传播级别的效果，这里可以先大致浏览一遍，关于事务传播的具体案例操作将会在实战部分进行详细的阐述。</p>
<table>
<thead>
<tr>
<th>特点</th>
<th>传播级别</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_REQUIRED</td>
<td>如果当前存在事务，则加入该事务；如果当前没有事务，则创建一个新的事务。</td>
</tr>
<tr>
<td>支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_SUPPORTS</td>
<td>如果当前存在事务，则加入该事务；如果当前没有事务，则以非事务的方式继续运行。</td>
</tr>
<tr>
<td>支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_MANDATORY</td>
<td>如果当前存在事务，则加入该事务；如果当前没有事务，则抛出异常。（mandatory：强制性）</td>
</tr>
<tr>
<td>不支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_REQUIRES_NEW</td>
<td>创建一个新的事务，如果当前存在事务，则把当前事务挂起。</td>
</tr>
<tr>
<td>不支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_NOT_SUPPORTED</td>
<td>以非事务方式运行，如果当前存在事务，则把当前事务挂起。</td>
</tr>
<tr>
<td>不支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_NEVER</td>
<td>以非事务方式运行，如果当前存在事务，则抛出异常。</td>
</tr>
<tr>
<td>其他情况</td>
<td>TransactionDefinition.PROPAGATION_NESTED</td>
<td>如果当前存在事务，则创建一个事务作为当前事务的嵌套事务来运行；如果当前没有事务，则该取值等价于TransactionDefinition.PROPAGATION_REQUIRED。</td>
</tr>
</tbody></table>
<h2 id="（5）Spring事务和传统的区别"><a href="#（5）Spring事务和传统的区别" class="headerlink" title="（5）Spring事务和传统的区别"></a>（5）Spring事务和传统的区别</h2><p>​    Spring事务和传统事务区别如下：</p>
<ol>
<li>不需要捕获SQLException，Spring会自动捕获异常并且转为相关的RuntimeException并且进行回滚。</li>
<li>通过Spring事务管理，可以极大化的减少配置，并且可以将事务委托为Spring进行管理。</li>
<li>传统事务会产生大量的侵入式代码，并且切换数据库对系统也是毁灭性打击。</li>
</ol>
<h2 id="（6）设计思路（个人理解）"><a href="#（6）设计思路（个人理解）" class="headerlink" title="（6）设计思路（个人理解）"></a>（6）设计思路（个人理解）</h2><p>​    设计思路部分是个人看完了Spring事务之后的一些思考补充，可以跳过。</p>
<p>​    上面简单的介绍了spring事务的大致特点，以及介绍了传统事务的特性以及并发事务的问题。</p>
<p>下面来看一下Spring是如何设计自己的事务的，这里读者可以停留下来思考一下，如果你是Spring事务的设计者，你会如何设计？这有利于你更深入的了解和巩固关于Spring事务的相关知识，这里大致说下个人的思考思路：</p>
<p>首先操作层面来看根据事务的特性，由于事务是多个连续的原子操作，所以肯定需要<strong>开启和提交事务</strong>这两个步骤。这是第一点。</p>
<p>然后我们在中途肯定需要对事务设置一些自己设置的属性，并且<strong>通过这些属性控制事务是否是只读的，不允许修改，控制是否允许使用事务</strong>等等，这是第二点。</p>
<p>我们需要考虑不用的数据库要如何兼容，也就是<strong>数据源要如何进行管理？</strong> 这时候肯定会想肯定分发给不同的数据源通过抽象事务管理器进行控制，同时会发现无论是回滚还是提交事务这些方法都是通用的，只是在数据库供应商底层的实现方式不同的而已，所以这里可以使用策略模式把事务的操作分发给具体的数据源实现，这是第三点。</p>
<p>有共同的方法所以需要使用 <strong>模板方法</strong>的模式控制抽象和模板方法的不同细节，提高代码复用性，这是第四点，模板方法并不算特别难。</p>
<p>如何实现嵌套事务的回滚，多线程访问的时候如何保持线程的隔离呢？这里我们最常想到的是<strong>ThreadLoacal</strong>，但是TheadLocal本身有点弱，我们是不是应该封装一下？这是第五点</p>
<p>所以最后我们从最顶层的抽象来看，完成一个事务其实只需要三个操作：<strong>1. 根据配置获取事务，2.执行操作，3. 提交或者回滚事务</strong>。其实归根结底，一个事务的底层抽象就是这三个动作，我们所有的事务设计都是围绕这三步来展开，这是最后一点，但是确实最复杂和抽象的。</p>
<p>看到这里你当然会说Spring的事务设计肯定怎么会才这么点，肯定比这个复杂多了，真正设计的时候肯定还会出现新的问题，并且有更加完善的架构。</p>
<p>我只能说在学习源码之前，脑子一定要有一套自己的思路，哪怕是错的也无所谓，静下心来看看设计者是如何思考的对照自己的思路进行纠正，否则很容易会被代码细节牵着走。</p>
<h1 id="四、编程式事务"><a href="#四、编程式事务" class="headerlink" title="四、编程式事务"></a>四、编程式事务</h1><p>​    编程式事务仅仅作为声明式事务的底层实现了解，现在基本不会用直接使用编程式事务，我们需要重点了解的部分在于核心的事务组件<strong>事务管理器</strong>。</p>
<h2 id="（1）实现方式"><a href="#（1）实现方式" class="headerlink" title="（1）实现方式"></a>（1）实现方式</h2><p>​    为了理解事务管理器，我们不得不啰嗦一下编程式事务的实现和使用方式，在代码中通常有下面两种实现方式：</p>
<ul>
<li>第一种：使用<strong>TransactionTemplate</strong>的模板类进行相关操作。</li>
<li>第二种：使用<strong>PlatformTransactionManager</strong> 控制事务的处理。</li>
</ul>
<p>那么哪一种方式更常用的？</p>
<p>其实两种方式<strong>都什么人用</strong>（嘿嘿，被我带进去了吧），因为声明式事务和他们相比方便一万倍，但是编程式事务是声明式事务的实现基础，所以我们不得静下心来不好好聊聊他是如何实现的。</p>
<h2 id="（2）配置方式"><a href="#（2）配置方式" class="headerlink" title="（2）配置方式"></a>（2）配置方式</h2><p>​    配置方式一般不怎么需要记忆，但是有时候会有奇葩的面试官会问这个东西看你有没有实际用过，其实多数情况都是不熟悉，所以这里列一个大致的模板：</p>
<blockquote>
<p>配置方式只有很老的项目才会这么干，强烈不建议去使用这种方式做配置。</p>
</blockquote>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 配置c3po连接池 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"dataSource"</span> <span class="attr">class</span>=<span class="string">"com.mchange.v2.c3p0.ComboPooledDataSource"</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 注入属性值 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driverClass"</span> <span class="attr">value</span>=<span class="string">"com.mysql.jdbc.Driver"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"jdbcUrl"</span> <span class="attr">value</span>=<span class="string">"jdbc:mysql://localhost:3306/xxxxx"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"user"</span> <span class="attr">value</span>=<span class="string">"xxx"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"xxxxx"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 编程式事务管理 --&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 配置事务管理器，必须是 PlatformTransactionManager 所支持的实现类 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"dataSourceTransactionManager"</span></span></span><br><span class="line"><span class="tag">		<span class="attr">class</span>=<span class="string">"org.springframework.jdbc.datasource.DataSourceTransactionManager"</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 注入dataSource --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"dataSource"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">&lt;!-- 配置事务管理器模板 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"transactionTemplate"</span></span></span><br><span class="line"><span class="tag">		<span class="attr">class</span>=<span class="string">"org.springframework.transaction.support.TransactionTemplate"</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 注入真正进行事务管理的事务管理器,name必须为 transactionManager否则无法注入 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"transactionManager"</span> <span class="attr">ref</span>=<span class="string">"dataSourceTransactionManager"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>小贴士：注意和声明式的配置方式区分。</p>
</blockquote>
<h2 id="（3）PlatformTransactionManager"><a href="#（3）PlatformTransactionManager" class="headerlink" title="（3）PlatformTransactionManager"></a>（3）PlatformTransactionManager</h2><h3 id="集成方式"><a href="#集成方式" class="headerlink" title="集成方式"></a>集成方式</h3><p>​    这里最快的处理方式是构建一个Spring boot web项目进行引入和直接使用，因为<strong>Spring在4.2版本之后SpringBoot项目可以不加任何注解添加事务支持（默认配置）</strong>，如果不知道如何操作，可以参考下面的步骤：</p>
<blockquote>
<p>快速搭建一个SpringBoot项目：</p>
<p><span class="exturl" data-url="aHR0cHM6Ly96aHVhbmxhbi56aGlodS5jb20vcC8xMDM1NDA0ODY=" title="https://zhuanlan.zhihu.com/p/103540486">Spring Boot快速搭建项目 - 知乎 (zhihu.com)<i class="fa fa-external-link"></i></span></p>
</blockquote>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- MYSQL --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="comment">&lt;!-- Spring Boot JDBC --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-jdbc<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>


<p>​    为了观察事务的操作，这里构建一张实验表：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`admin`</span> (</span><br><span class="line">  <span class="string">`id`</span> <span class="built_in">int</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT,</span><br><span class="line">  <span class="string">`username`</span> <span class="built_in">varchar</span>(<span class="number">50</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  <span class="string">`password`</span> <span class="built_in">varchar</span>(<span class="number">50</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>)</span><br><span class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> AUTO_INCREMENT=<span class="number">2</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8mb3;</span><br></pre></td></tr></table></figure>


<p>​    快速编写一个单元测试来验证事务是否生效：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 单元测试</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TransactionTemplateTest</span>()</span>&#123;</span><br><span class="line">  <span class="meta">@Autowired</span></span><br><span class="line">  <span class="keyword">private</span> ProgrammaticTrasaction programmaticTrasaction;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 使用TransactionTemplate 进行事务处理</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="meta">@Test</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">transactionTemplateTest</span><span class="params">()</span></span>&#123;</span><br><span class="line">    programmaticTrasaction.insert();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ProgrammaticTrasaction</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 异常触发开关</span></span><br><span class="line">  	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> EXCEPTION_FLAG = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> JdbcTemplate jdbcTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> TransactionTemplate transactionTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insert</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">// 1. 构建事务管理器，同时使用系统的数据源进行设置</span></span><br><span class="line">        PlatformTransactionManager platformTransactionManager = <span class="keyword">new</span> DataSourceTransactionManager(Objects.requireNonNull(jdbcTemplate.getDataSource()));</span><br><span class="line">        <span class="comment">// 2. 配置事务的属性，比如事务的隔离级别，事务的超时时间以及隔离方式等等</span></span><br><span class="line">        TransactionDefinition transactionDefinition = <span class="keyword">new</span> DefaultTransactionDefinition();</span><br><span class="line">        <span class="comment">// 3. 开启事务，通过默认的事务属性配置，调用platformTransactionManager.getTransaction开启事务操作，此时获取到事务的状态 TransactionStatus</span></span><br><span class="line">        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);</span><br><span class="line">        <span class="comment">// 4. 执行和事务有关操作，这里用新增作为处理</span></span><br><span class="line">        System.err.println(<span class="string">"查询数据列表"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            System.err.println(jdbcTemplate.queryForList(<span class="string">"select * from admin"</span>));</span><br><span class="line">            <span class="comment">// 注意，jdbctemplate 把所有对于数据的改动操作统一为 update 操作，而查询则以 query 开头</span></span><br><span class="line">            jdbcTemplate.update(<span class="string">"insert into admin (id, username, password) values (51, '老王', '123')"</span>);</span><br><span class="line">            jdbcTemplate.update(<span class="string">"insert into admin (id, username, password) values (21, '老张', '222')"</span>);</span><br><span class="line">            <span class="comment">// 5. 提交事务</span></span><br><span class="line">            platformTransactionManager.commit(transaction);</span><br><span class="line">            <span class="comment">// 6. 手动抛出异常进行回滚</span></span><br><span class="line">          	<span class="comment">//if(EXCEPTION_FLAG)&#123;</span></span><br><span class="line">            <span class="comment">//  throw new RuntimeException("手动抛出异常");</span></span><br><span class="line">            <span class="comment">//&#125;</span></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="comment">// 6. 我们需要使用事务管理器的rollback方法回滚整个事务</span></span><br><span class="line">            System.err.println(<span class="string">"异常：触发事务回滚"</span>);</span><br><span class="line">            platformTransactionManager.rollback(transaction);</span><br><span class="line">        &#125;</span><br><span class="line">        System.err.println(<span class="string">"插入数据之后"</span>);</span><br><span class="line">        System.err.println(jdbcTemplate.queryForList(<span class="string">"select * from admin"</span>));</span><br><span class="line"></span><br><span class="line">    &#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">    第一次执行</span></span><br><span class="line"><span class="comment">    查询数据列表</span></span><br><span class="line"><span class="comment">    [&#123;id=1, username=admin, password=123456&#125;]</span></span><br><span class="line"><span class="comment">    插入数据之后</span></span><br><span class="line"><span class="comment">    [&#123;id=1, username=admin, password=123456&#125;, &#123;id=21, username=老张, password=222&#125;, &#123;id=51, username=老王, password=123&#125;]</span></span><br><span class="line"><span class="comment">    第二次执行：</span></span><br><span class="line"><span class="comment">    查询数据列表</span></span><br><span class="line"><span class="comment">    [&#123;id=1, username=admin, password=123456&#125;, &#123;id=21, username=老张, password=222&#125;, &#123;id=51, username=老王, password=123&#125;]</span></span><br><span class="line"><span class="comment">    触发事务回滚</span></span><br><span class="line"><span class="comment">    插入数据之后</span></span><br><span class="line"><span class="comment">[&#123;id=1, username=admin, password=123456&#125;, &#123;id=21, username=老张, password=222&#125;, &#123;id=51, username=老王, password=123&#125;]</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>​    上面的代码看起来和我们编写模板代码操作没什么区别，其实spring 为我们做好了不少的准备和繁琐的基础工作，下面我们对spring事务的核心代码分析一波。</p>
<h3 id="源码解析"><a href="#源码解析" class="headerlink" title="源码解析"></a>源码解析</h3><p>​    下面是从网络上找到的一张关于编程式事务的接口图，比较形象的说明了Spring事务的整体设计，后续声明式事务和各种模板操作类其实都是基于下面这个结构的扩展：</p>
<p><img src="https://adong-picture.oss-cn-shenzhen.aliyuncs.com/adong/20220902105321.png" alt=""></p>
<p>​    <strong>PlatformTransactionManager 事务管理器</strong></p>
<p>​    首先我们来看下事务管理器接口的结构图，这里需要注意的是<strong>TransactionManager</strong> 这个接口是一个标记接口，标记为Spring的事务管理接口，其他所有的对象要介入spring的事务必须实现此标记接口（当然通常是实现PlatformTransactionManager接口，或者扩展抽象的默认事务管理器实现）。</p>
<blockquote>
<p>提示：不同spring版本类图可能会有区别。</p>
</blockquote>
<p><img src="https://adong-picture.oss-cn-shenzhen.aliyuncs.com/adong/20220902105414.png" alt=""></p>
<p>​    下面是PlatformTransactionManager 事务管理器接口，也是spring事务管理机制的核心接口。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">PlatformTransactionManager</span> <span class="keyword">extends</span> <span class="title">TransactionManager</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">   开启一个新的事务</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  <span class="function">TransactionStatus <span class="title">getTransaction</span><span class="params">(@Nullable TransactionDefinition definition)</span></span></span><br><span class="line"><span class="function">      <span class="keyword">throws</span> TransactionException</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   提交一个事务</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">commit</span><span class="params">(TransactionStatus status)</span> <span class="keyword">throws</span> TransactionException</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   事务回滚</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">rollback</span><span class="params">(TransactionStatus status)</span> <span class="keyword">throws</span> TransactionException</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>从类图可以看到，这里存在许多的实现类，这里我们挑几个比较常见的类进行介绍：</p>
<ul>
<li><strong>JtaTransactionManager</strong> ：jta事务管理器，继承自一个抽象的事务管理实现，如果你需要使用分布式的事务管理进行操作，可以使用这个事务管理器，当然多数情况它派不上用场。</li>
</ul>
<blockquote>
<p>小贴士：</p>
<p>​    <strong>JPA是啥玩意？</strong>JPA本身是一个规范，基于此规范实现的产品有：Hibernate, Eclipselink, Toplink, Spring Data JPA, etc等，其中最典型的实现是ORM的鼻祖Hibernate。如果想要更多了解JPA，可以看看这篇客：<span class="exturl" data-url="aHR0cHM6Ly9qdWVqaW4uY24vcG9zdC82ODQ0OTAzODIyNDIzNDA4NjQ3" title="https://juejin.cn/post/6844903822423408647">什么是JPA？Java Persistence API简介<i class="fa fa-external-link"></i></span>。</p>
<p>​    <strong>JTA又是啥玩意？</strong>注意不要和JPA搞混了，JTA指的是允许应用程序执行<strong>分布式事务管理</strong> ，在两个或多个网络计算机资源上访问并且更新数据，JDBC驱动程序的加入JTA支持极大地增强了数据访问能力，如果对于JTA细节和规范了解，可以看文章最开头的博客，这里不再过多介绍。</p>
</blockquote>
<ul>
<li><strong>DataSourceTransactionManager</strong> ：如果使用了数据源进行操作，比如使用了jdbcTemplate，mybatis这种框架的时候需要使用此事务管理器。</li>
<li><strong>CciLocalTransactionManager</strong> ：CCI （Common Client Interface）是应用程序用来与连接器交互并与EIS通信的接口。同样还为本地事务划界提供了API，Spring提供CCI的支持主要是为了同价通用的资源和事务管理工具，但是其实用的十分少。</li>
</ul>
<p><strong>Spring是如何获取事务的？</strong></p>
<p>​    如何让Spring获取不同数据源的事务的呢？核心在于事务管理器的一个默认实现<strong>AbstractPlatformTransactionManager</strong> 类，默认实现了获取事务的抽象逻辑，将具体的获取逻辑分发到，下面为方法<code>org.springframework.transaction.support.AbstractPlatformTransactionManager#getTransaction</code>方法的执行流程：</p>
<ol>
<li>检查是否传递事务属性TransactionDefinition，如果没有则使用默认配置。</li>
<li>以DataSourceTransactionManager数据源为例，通过<code>DataSourceTransactionManager#doGetTransaction()</code>方法，构建一个事务对象，同时设置相关的属性，通过TransactionSynchronizationManager#getResource() <strong>同步</strong>获取ConnectionHolder（连接器）对象 ，<code>TransactionSynchronizationManager.getResource()</code>方法比较关键，Spring将连接器统一配置在一个NamedThreadLocal的全局线程共享资源当中，同时由于key有可能是一个动态的代理对象，所以key的获取会尝试解包动态代理来获取实际目标对象或者直接使用透明代理两种形式，当NamedThreadLocal中配置的连接器被获取到则进行返回（此时会额外检查当前线程是否还存在连接器存在于全局变量中，如果不存在则移除当前的线程资源释放内存）。</li>
<li>之后到代码逻辑较为简单，通过事务属性对象TransactionDefinition 进行事务的传播机制判断，然后便是熟悉的开启事务和执行sql以及返回结果等等一系列操作的模板代码，这里结合了策略和模板的设计模式，代码都比较好懂。</li>
<li>在提交事务最后有一步比较特殊，在事务提交之后如果发现当前的连接是一个新的连接，则会调用<strong>TransactionSynchronizationManager#bindResource</strong>  将当前的连接器进行绑定，这样可以保证同一线程内传播的是同一个事务。</li>
</ol>
<p>​    下面是获取事务的抽象方法，下面是关于获取事务方法的细节：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">final</span> TransactionStatus <span class="title">getTransaction</span><span class="params">(@Nullable TransactionDefinition definition)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> TransactionException </span>&#123;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 检查是否传递事务属性TransactionDefinition，如果没有则使用默认配置。</span></span><br><span class="line">		TransactionDefinition def = (definition != <span class="keyword">null</span> ? definition : TransactionDefinition.withDefaults());</span><br><span class="line">		<span class="comment">// 由具体的数据源获取一个事务，比较常用的是</span></span><br><span class="line">		Object transaction = doGetTransaction();</span><br><span class="line">		<span class="keyword">boolean</span> debugEnabled = logger.isDebugEnabled();</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> (isExistingTransaction(transaction)) &#123;</span><br><span class="line">			<span class="comment">// 检查当前是否已经存在事务，则根据事务的传播等级进行判断，新建事务或者抛出异常等处理</span></span><br><span class="line">			<span class="keyword">return</span> handleExistingTransaction(def, transaction, debugEnabled);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 检查事务超时时间是否设置 </span></span><br><span class="line">		<span class="keyword">if</span> (def.getTimeout() &lt; TransactionDefinition.TIMEOUT_DEFAULT) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> InvalidTimeoutException(<span class="string">"Invalid transaction timeout"</span>, def.getTimeout());</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 如果没有发现事务，则检查是否事务传播级别异常</span></span><br><span class="line">		<span class="keyword">if</span> (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> IllegalTransactionStateException(</span><br><span class="line">					<span class="string">"No existing transaction found for transaction marked with propagation 'mandatory'"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||</span><br><span class="line">				def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||</span><br><span class="line">				def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) &#123;</span><br><span class="line">			SuspendedResourcesHolder suspendedResources = suspend(<span class="keyword">null</span>);</span><br><span class="line">			<span class="keyword">if</span> (debugEnabled) &#123;</span><br><span class="line">				logger.debug(<span class="string">"Creating new transaction with name ["</span> + def.getName() + <span class="string">"]: "</span> + def);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="comment">// 开启事务</span></span><br><span class="line">				<span class="keyword">return</span> startTransaction(def, transaction, debugEnabled, suspendedResources);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">catch</span> (RuntimeException | Error ex) &#123;</span><br><span class="line">				resume(<span class="keyword">null</span>, suspendedResources);</span><br><span class="line">				<span class="keyword">throw</span> ex;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="comment">// 创建“空”事务：没有实际事务，但可能是同步的。</span></span><br><span class="line">			<span class="keyword">if</span> (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT &amp;&amp; logger.isWarnEnabled()) &#123;</span><br><span class="line">				logger.warn(<span class="string">"Custom isolation level specified but no actual transaction initiated; "</span> +</span><br><span class="line">						<span class="string">"isolation level will effectively be ignored: "</span> + def);</span><br><span class="line">			&#125;</span><br><span class="line">            </span><br><span class="line">			<span class="keyword">boolean</span> newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);</span><br><span class="line">			<span class="keyword">return</span> prepareTransactionStatus(def, <span class="keyword">null</span>, <span class="keyword">true</span>, newSynchronization, debugEnabled, <span class="keyword">null</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<p>​    最后我们把上面的描述简化为伪代码的形式进行解释：</p>
<blockquote>
<p>DataSource 事务对象，代表一个ConnectionHolder，用作 DataSourceTransactionManager 的事务对象。</p>
<p>小知识：如果Springboot没有配置数据源，默认会使用一个叫做 HikariPool的数据源，这个配置<strong>在2.0之后为默认值</strong>。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用threadlocal 绑定一个全局共享的全局变量</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocal&lt;Map&lt;Object, Object&gt;&gt; resources =</span><br><span class="line">      <span class="keyword">new</span> NamedThreadLocal&lt;&gt;(<span class="string">"Transactional resources"</span>);</span><br><span class="line"></span><br><span class="line">DataSource dataSource = platformTransactionManager.getDataSource();</span><br><span class="line"><span class="comment">// 下面为事务管理器获取细节 ====&gt;</span></span><br><span class="line"><span class="comment">// 从全局共享变量获取当前线程对应的资源池</span></span><br><span class="line">Map map = resources.get();</span><br><span class="line"><span class="comment">// actualKey =&gt; 为实际的对象（aop为实际对象）</span></span><br><span class="line">ConnectionHolder localConnectionHolder = resources.get(actualKey, map.get(actualKey));</span><br><span class="line"><span class="keyword">if</span>(map.isEmpty())&#123;</span><br><span class="line"><span class="comment">// 额外检查当前线程是否还存在连接器存在于全局变量中，如果不存在则移除当前的线程资源释放，避免被释放的线程对象堆积在共享资源</span></span><br><span class="line">  resources.remove();</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//设置手动提交事务</span></span><br><span class="line">localConnectionHolder.setAutoCommit(<span class="keyword">false</span>);</span><br><span class="line">map.put(datasource,connection);</span><br><span class="line">resources.set(map);</span><br><span class="line"><span class="comment">// &lt;==========</span></span><br></pre></td></tr></table></figure>


<p>​    再一次强调整个spring事务的核心部分是AbstractPlatformTransactionManager，它定义了spring获取事务的绝大多数的公用逻辑，而具体关于获取，提交，回滚等等细节则需要由子类的具体事务管理器进行实现。</p>
<p>​    最后，编程式事务在以前使用还是十分常见的（因为也没有别的工具），只不过spring推出注解式的声明式事务太好用了才逐渐淡出了视野，但是学习这些内容有助于更好的理解spring是如何实现注解式事务的，因为核心实现还是通过事务管理器来完成。</p>
<blockquote>
<p>小贴士：看到这里建议休息一下整理一下思路，出去倒杯水回来慢慢接着看。</p>
</blockquote>
<h2 id="（4）TransactionTemplate"><a href="#（4）TransactionTemplate" class="headerlink" title="（4）TransactionTemplate"></a>（4）TransactionTemplate</h2><p>​    现在我们来看下第二种方式TransactionTemplate，第二种方式其实是对于纯手动形式的进一步封装，我们可以发现事务管理器的模板代码其实可以省出开启事务和提交事务和回滚的步骤，这些步骤依然会出现大量的模板代码，并且客户端也不喜欢手动开启和关闭事务，Spring针对此进行改进出现了<strong>TransactionTemplate</strong> 事务的模板方法类，下面我们根据一个实际的运行代码来讲解一下它的用法：</p>
<h3 id="使用方式"><a href="#使用方式" class="headerlink" title="使用方式"></a>使用方式</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">// 1.2 不需要使用事务管理器，而是直接在transactionTemplate内部集成</span></span><br><span class="line">        <span class="comment">// 3. 区别点，这里使用了transactionTemplate进行事务的开启和控制，下面介绍他的两种主要使用方式</span></span><br><span class="line">        <span class="comment">// 3.1  transactionTemplate.executeWithoutResult(Consumer&lt;TransactionStatus&gt; action)：</span></span><br><span class="line">        <span class="comment">// 没有返回值的，需传递一个Consumer对象，在accept方法中做业务操作。（类似切面）</span></span><br><span class="line">        <span class="comment">// 3.2 &lt;T&gt; T execute(TransactionCallback&lt;T&gt; action)：有返回值的，需要传递一个TransactionCallback对象，在doInTransaction方法中做业务操作</span></span><br><span class="line">        <span class="comment">// 调用execute方法或者executeWithoutResult方法执行完毕之后，事务管理器会自动提交事务或者回滚事务。</span></span><br><span class="line">        <span class="comment">// 事务在什么情况下会进行回滚？需要满足下面的条件：</span></span><br><span class="line">        <span class="comment">// （1）transactionStatus.setRollbackOnly();将事务状态标注为回滚状态</span></span><br><span class="line">        <span class="comment">// （2）execute方法或者executeWithoutResult方法内部抛出异常</span></span><br><span class="line">        <span class="comment">//  什么时候事务会提交？</span></span><br><span class="line">        <span class="comment">//  方法没有异常 &amp;&amp; 未调用过transactionStatus.setRollbackOnly();</span></span><br><span class="line">        System.err.println(<span class="string">"事务处理前"</span>);</span><br><span class="line">        System.err.println(jdbcTemplate.queryForList(<span class="string">"select * from admin"</span>));</span><br><span class="line">        <span class="comment">// 第一种使用方式</span></span><br><span class="line">        transactionTemplate.executeWithoutResult(transactionStatus -&gt; &#123;</span><br><span class="line">            jdbcTemplate.update(<span class="string">"update admin set username ='test2'  where id = '51'"</span>);</span><br><span class="line"></span><br><span class="line">            jdbcTemplate.update(<span class="string">"update admin set username ='test2',password='1111'  where id = '21'"</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="comment">// 第二种使用方式</span></span><br><span class="line">        DefaultTransactionStatus execute = (DefaultTransactionStatus) transactionTemplate.execute((TransactionCallback&lt;Object&gt;) status -&gt; &#123;</span><br><span class="line">            jdbcTemplate.update(<span class="string">"update admin set username ='test2'  where id = '51'"</span>);</span><br><span class="line"></span><br><span class="line">            jdbcTemplate.update(<span class="string">"update admin set username ='test2',password='1111'  where id = '21'"</span>);</span><br><span class="line">            <span class="keyword">return</span> status;</span><br><span class="line">        &#125;);</span><br><span class="line">        System.err.println(<span class="string">"事务处理后"</span>);</span><br><span class="line">        System.err.println(jdbcTemplate.queryForList(<span class="string">"select * from admin"</span>));</span><br><span class="line">    &#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">        事务处理前</span></span><br><span class="line"><span class="comment">        [&#123;id=1, username=admin, password=123456&#125;, &#123;id=21, username=老张, password=222&#125;, &#123;id=51, username=老王, password=123&#125;]</span></span><br><span class="line"><span class="comment">        事务处理后</span></span><br><span class="line"><span class="comment">        [&#123;id=1, username=admin, password=123456&#125;, &#123;id=21, username=test2, password=1111&#125;, &#123;id=51, username=test2, password=123&#125;]</span></span><br><span class="line"><span class="comment">    */</span></span><br></pre></td></tr></table></figure>


<p>​    可以看到，使用<strong>TransactionTemplate</strong>  的方式缩减了很多代码，我们不需要关心事务开启和提交的细节，只需要关心事务的处理操作即可。</p>
<h3 id="源码解析-1"><a href="#源码解析-1" class="headerlink" title="源码解析"></a>源码解析</h3><p>​    下面按照同样源码来解释一下这个操作的大致处理流程，这里可能会感觉我擦这么神奇，不用事务管理器，也不需要设置属性了，那要怎么设置属性？ 其实只不过是把所有的工作交给<strong>TransactionTemplate</strong> 去做了，为了验证我们可以对比<strong>DefaultTransactionDefinition</strong> 和<strong>TransactionTemplate</strong> 中的方法，可以发现他们的方法基本一致。（其实<strong>TransactionTemplate</strong> 就是继承了<strong>DefaultTransactionDefinition</strong> ）。多数情况下我们通过@Configuration注入Bean的方式，为全局的TransactionTemplate设置一些默认配置。</p>
<blockquote>
<p>其实从个人角度来看这里使用继承的方式实现spring相关的事务配置并不是很好，而是使用一个配置构造器完成配置的中转或者使用组合TransactionDefinition的方式比较恰当。</p>
</blockquote>
<p><strong>DefaultTransactionDefinition</strong> ：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211229220810.png" alt=""></p>
<p><strong>TransactionTemplate</strong> ：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211229220833.png" alt=""></p>
<p>​    下面我们再来看下它的类图，可以看到他在扩展事务属性类的基础上实现了新的接口：TransactionOpration，这也是一个关键接口，另外<strong>TransactionTemplate</strong> 可以进行事务的各种操作的原因是它内部组合了PlatformTransactionManager的对象，所以所有的事务管理实际上还是通过PlatformTransactionManager对象进行管理的，换汤不换药：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211229220848.png" alt=""></p>
<p>​    下面是TransactionOperations的方法签名，注意Spring5对于这个接口做过改动和扩展，旧版本的包可能内容不同：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TransactionOperations</span></span>&#123;</span><br><span class="line"> 	<span class="comment">/**</span></span><br><span class="line"><span class="comment"> 	带返回值的方法</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  <span class="meta">@Nullable</span></span><br><span class="line">	&lt;T&gt; <span class="function">T <span class="title">execute</span><span class="params">(TransactionCallback&lt;T&gt; action)</span> <span class="keyword">throws</span> TransactionException</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">  jdk8 的接口默认方法,不带返回值的使用方式</span></span><br><span class="line"><span class="comment">  <span class="doctag">@since</span>：5.2</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  <span class="function"><span class="keyword">default</span> <span class="keyword">void</span> <span class="title">executeWithoutResult</span><span class="params">(Consumer&lt;TransactionStatus&gt; action)</span> <span class="keyword">throws</span> TransactionException </span>&#123;</span><br><span class="line">		execute(status -&gt; &#123;</span><br><span class="line">			action.accept(status);</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">		返回 TransactionOperations 接口的实现，该接口在没有实际事务的情况下执行给定的 TransactionCallback。通常在测试的时候使用：该行为相当于在没有实际事务 (PROPAGATION_SUPPORTS) 和没有同步 (SYNCHRONIZATION_NEVER) 的情况下使用事务管理器运行。</span></span><br><span class="line"><span class="comment">  对于具有实际事务处理的 TransactionOperations 实现，将 TransactionTemplate 与适当的 PlatformTransactionManager 一起使用。</span></span><br><span class="line"><span class="comment">  <span class="doctag">@since</span>：5.2</span></span><br><span class="line"><span class="comment">  <span class="doctag">@see</span>：</span></span><br><span class="line"><span class="comment">  TransactionDefinition.PROPAGATION_SUPPORTS, </span></span><br><span class="line"><span class="comment">  AbstractPlatformTransactionManager.SYNCHRONIZATION_NEVER, </span></span><br><span class="line"><span class="comment">  TransactionTemplate</span></span><br><span class="line"><span class="comment">		</span></span><br><span class="line"><span class="comment">	*/</span></span><br><span class="line">  <span class="function"><span class="keyword">static</span> TransactionOperations <span class="title">withoutTransaction</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> WithoutTransactionOperations.INSTANCE;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    再来看一下<strong>TransactionTemplate</strong> ，代码相对简单，相信读者只要了解原始的事务操作模板方法就可以看懂：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">说明：</span></span><br><span class="line"><span class="comment">  在事务中执行给定回调对象指定的操作。允许返回在事务中创建的结果对象，</span></span><br><span class="line"><span class="comment">  即域对象或域对象的集合。回调抛出的 RuntimeException 被视为强制回滚的异常。</span></span><br><span class="line"><span class="comment">  这样的异常会传播到模板的调用者。</span></span><br><span class="line"><span class="comment">参数：</span></span><br><span class="line"><span class="comment">  action - 指定事务操作的回调对象</span></span><br><span class="line"><span class="comment">  返回：</span></span><br><span class="line"><span class="comment">    回调返回的结果对象，如果没有，则为 null</span></span><br><span class="line"><span class="comment">    抛出：</span></span><br><span class="line"><span class="comment">      TransactionException - 在初始化、回滚或系统错误的情况下</span></span><br><span class="line"><span class="comment">      RuntimeException - 由 TransactionCallback 抛出</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line">  <span class="meta">@Nullable</span></span><br><span class="line">  <span class="keyword">public</span> &lt;T&gt; <span class="function">T <span class="title">execute</span><span class="params">(TransactionCallback&lt;T&gt; action)</span> <span class="keyword">throws</span> TransactionException </span>&#123;</span><br><span class="line">  <span class="comment">// 检查当前是否存在事务管理器（不允许为空）</span></span><br><span class="line">    Assert.state(<span class="keyword">this</span>.transactionManager != <span class="keyword">null</span>, <span class="string">"No PlatformTransactionManager set"</span>);</span><br><span class="line">  <span class="comment">// 如果当前事务管理器支持自动回调处理，则使用事务管理器自动回调方法的实现，CallbackPreferringPlatformTransactionManager 类扩展自PlatformTransactionManager，公开了在事务中执行给定回调的方法。</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.transactionManager <span class="keyword">instanceof</span> CallbackPreferringPlatformTransactionManager) &#123;</span><br><span class="line">      <span class="keyword">return</span> ((CallbackPreferringPlatformTransactionManager) <span class="keyword">this</span>.transactionManager).execute(<span class="keyword">this</span>, action);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 如果不支持自动回调，则转入到传统的处理模式，这部分代码和原始的事务管理操作类似</span></span><br><span class="line">      TransactionStatus status = <span class="keyword">this</span>.transactionManager.getTransaction(<span class="keyword">this</span>);</span><br><span class="line">      T result;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// 核心部分，使用action的函数式调用实现内部的事务处理</span></span><br><span class="line">        result = action.doInTransaction(status);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (RuntimeException | Error ex) &#123;</span><br><span class="line">        <span class="comment">// 如何出现 RuntimeException 或者 错误 回滚</span></span><br><span class="line">        rollbackOnException(status, ex);</span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">         <span class="comment">// 异常则根据事务级别进行回滚</span></span><br><span class="line">        rollbackOnException(status, ex);</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> UndeclaredThrowableException(ex, <span class="string">"TransactionCallback threw undeclared checked exception"</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 如果没有出现异常，则正常提交</span></span><br><span class="line">      <span class="keyword">this</span>.transactionManager.commit(status);</span><br><span class="line">      <span class="comment">// 返回事务执行的结果</span></span><br><span class="line">      <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>


<p>​    了解带返回值execute方法之后，我们来了解一下不带返回值的方法<code>executeWithoutResult()</code>，它的实现代码就更为简洁了，从最新版本的代码可以看到其实后续的版本有做函数式表达式重构，所以如果jdk版本比较低可能出现不兼容的情况：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">在事务中执行给定 Runnable 指定的操作。</span></span><br><span class="line"><span class="comment">如果需要从回调中返回一个对象或从回调中访问 TransactionStatus，可以改用 execute(TransactionCallback)。</span></span><br><span class="line"><span class="comment">这样的变体类似于使用 TransactionCallbackWithoutResult 但具有针对常见情况的简化签名 - 并且可以方便地与 Java 8 lambda 表达式一起使用。</span></span><br><span class="line"><span class="comment">参数：</span></span><br><span class="line"><span class="comment">action - 指定事务操作的 Runnable</span></span><br><span class="line"><span class="comment">抛出：</span></span><br><span class="line"><span class="comment">TransactionException - 在初始化、回滚或系统错误的情况下</span></span><br><span class="line"><span class="comment">RuntimeException - 如果由 Runnable 抛出</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">default</span> <span class="keyword">void</span> <span class="title">executeWithoutResult</span><span class="params">(Consumer&lt;TransactionStatus&gt; action)</span> <span class="keyword">throws</span> TransactionException </span>&#123;</span><br><span class="line">    execute(status -&gt; &#123;</span><br><span class="line">      action.accept(status);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<h2 id="（5）小结"><a href="#（5）小结" class="headerlink" title="（5）小结"></a>（5）小结</h2><p>​    最后我们来小结一波上面的内容，这一节开始我们了解了传统编程式事务的操作，可以看到虽然Spring已经封装开启和关闭事务的细节，也封装了关于JDBC操作的模板代码，但是我们如果使用编程式事务还是会产生大量的侵入式代码，这也不符合单一职责的原则。</p>
<p>编程式事务实现的几个特点：</p>
<ol>
<li>事务的传播机制基于<code>AbstractPlatformTransactionManager#getTransaction()</code>方法，通过不同的事务传播等级设置进行事务的管理。</li>
<li>为了保证同一个线程使用的连接资源的一致性，Spring使用了<code>ThreadLocal</code>作为全局共享变量的存储，实现线程之间的事务隔离，同时防止并发事务的问题。</li>
<li><strong>TransactionTemplate</strong>  可以看作是对于<code>PlatformTransactionManager</code> 事务管理器的二次封装并且扩展了回调式的事务操作。</li>
</ol>
<p>​    再次强调花费大量篇幅介绍并不是说推荐大家使用，而是使用编程式事务更有助于我们了解声明式事务的使用，下面我们来了解一下声明式事务的使用。</p>
<h1 id="五、声明式事务"><a href="#五、声明式事务" class="headerlink" title="五、声明式事务"></a>五、声明式事务</h1><p>​    声明式事务的使用就十分简单易懂了，就是我们熟悉的<code>@Transactional</code>注解，做到了不侵入的添加和去除事务管理支持，声明式事务的实现使用了AOP，本质其实就是在执行被注解的事务方法前进行拦截操作，声明式事务有如下的优缺点：</p>
<p>​    优点： 简单快速注入事务，无需改动任何业务代码。</p>
<p>​    缺点：和spring aop的缺点一致，<strong>只能针对方法级别进行事务控制</strong> ，并且只能通过Spring代理对象才能使用声明式事务，如果自己new对象接入事务这样做是不会生效的（切记），具有一定的局限性。</p>
<h2 id="（1）如何使用？"><a href="#（1）如何使用？" class="headerlink" title="（1）如何使用？"></a>（1）如何使用？</h2><p>​    不同的项目配置方式不同，需要针对具体的项目环境使用，目前主流是使用微服务，这里其实更加推荐使用@Bean类配置的方式注入事务管理的相关功能，比如配置事务管理器。如果你是SpringBoot并且版本比较新，那就非常简单了，直接加注解使用即可。</p>
<blockquote>
<p>小贴士：如果你使用的是springboot2.0之后的项目，并且如果在依赖里面有<strong>spring-data-*</strong>或者 <strong>spring-tx</strong>事务有关的依赖，则默认会开启声明式事务。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">  <span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">  <span class="title">public</span> <span class="title">void</span> <span class="title">testAdd</span>() </span>&#123;</span><br><span class="line">      <span class="comment">//dosomething</span></span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>​    但是如果Spring Boot的版本比较低或者一些比较旧的项目，则需要手动开启一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableTransactionManagement</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MySpringConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> PlatformTransactionManager <span class="title">txManager</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// dosomething 可以自己配置事一些事务管理器的配置。</span></span><br><span class="line">        <span class="keyword">return</span> yourTxManager; </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    顺带一提，如果我们想要在注解的方法里面使用编程式的TransactionAspectSupport类里面的方法手动回滚事务，可以使用下面的方法进行回滚（但是建议不要这么使用）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createCourseDefaultRatingProgramatic</span><span class="params">(Course course)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">       courseDao.create(course);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        <span class="comment">// 手动回滚</span></span><br><span class="line">       TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="Transactional注解介绍"><a href="#Transactional注解介绍" class="headerlink" title="@Transactional注解介绍"></a>@Transactional注解介绍</h3><p>​    我们来看一下关于<code>@Tralsactional</code>拥有哪些配置：</p>
<ul>
<li>value：别名，指定使用的事务管理器的Bean</li>
<li>transactionManager：指定事务的限定符值。可用于确定目标事务管理器，匹配特定 TransactionManager bean 定义的限定符值（或 bean 名称）。</li>
<li><strong>propagation：用于指定事务的传播级别，核心和常用属性</strong></li>
<li>isolation：事务的隔离级别，如果没有特殊指定，则默认按照数据库的级别</li>
<li>timeout：代表当前事务的超时时间（以秒为单位），默认为底层事务系统的默认超时时间（注意代码给了1秒的默认值）。专为与 <code>Propagation.REQUIRED</code>或 <code>Propagation.REQUIRES_NEW</code> 一起使用而设计，需要注意的是<strong>仅适用于新启动的事务</strong>。</li>
<li>readOnly：默认为false，如果设置为true，则只运行执行非update操作，如果碰到Update的操作反而会抛出异常。此配置方式有利于提高事务执行效率，如果不需要update相关事务，可以将此设置为true。</li>
<li>rollbackFor：根据指定的Class异常类进行回滚，如果没有设置，默认为运行时异常，但是需要注意必须是able的子类。</li>
<li>rollbackForClassName：必须是able的子类完全限定类名的子字符串，目前不支持通配符。例如，<code>ServletException</code>的值将匹配 <code>javax.servlet.ServletException</code> 及其子类。</li>
<li>noRollbackFor：和rollbackFor刚好相反。</li>
<li>noRollbackForClassName：和rollbackForClassName刚好相反。</li>
</ul>
<p>​    如果在多个地方使用了相同的注解，但是我们又不想总是复制粘贴大量的重复注解配置的时候，有一种方式是使用自定义注解的方式，这里简单了解即可。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.METHOD, ElementType.TYPE&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Transactional</span>(transactionManager = <span class="string">"order"</span>, label = <span class="string">"causal-consistency"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> OrderTx &#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Target</span>(&#123;ElementType.METHOD, ElementType.TYPE&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Transactional</span>(transactionManager = <span class="string">"account"</span>, label = <span class="string">"retryable"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> AccountTx &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="监听器绑定事件"><a href="#监听器绑定事件" class="headerlink" title="监听器绑定事件"></a>监听器绑定事件</h3><p>​    监听器事务绑定事件需要<strong>Spring4.2以上才支持</strong>，需要<strong>Spring4.2以上才支持</strong>，需要<strong>Spring4.2以上才支持</strong>，很重要，所以特意强调三遍。通常情况下使用<code>@EventListener</code>注解注册常规事件侦听器。如果需要将其绑定到事务也可以用<code>@TransactionalEventListener</code>，这样可以实现监听器的事务操作。</p>
<p>​    下面是官方提供的案例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyComponent</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@TransactionalEventListener</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleOrderCreatedEvent</span><span class="params">(CreationEvent&lt;Order&gt; creationEvent)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    @TransactionalEventListener这个注解有个比较特殊的熟悉就是<code>phase</code>这个属性：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">TransactionPhase <span class="title">phase</span><span class="params">()</span> <span class="keyword">default</span> TransactionPhase.AFTER_COMMIT</span>;</span><br></pre></td></tr></table></figure>

<p>​    这个属性支持事务绑定到指定的阶段，包含下面几个级别：</p>
<ul>
<li><p>BEFORE_COMMIT</p>
</li>
<li><p>AFTER_COMMIT（默认）</p>
</li>
<li><p>AFTER_ROLLBACK</p>
</li>
<li><p>AFTER_COMPLETION</p>
</li>
</ul>
<p>​    监听器使用事务的场景个人目前没有碰到，所以这里仅仅根据官方文档简单翻译介绍了一番。</p>
<h3 id="JTA的集成"><a href="#JTA的集成" class="headerlink" title="JTA的集成"></a>JTA的集成</h3><p>​    如果需要集成JTA，那么配置文件不能使用某一特定的资源，而是需要配合JNDI同时配合<strong>JtaTransactionManager</strong>事务管理器进行全局的事务管理，下面我们来看一下配置的方式。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:jee</span>=<span class="string">"http://www.springframework.org/schema/jee"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        https://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/jee</span></span></span><br><span class="line"><span class="tag"><span class="string">        https://www.springframework.org/schema/jee/spring-jee.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">jee:jndi-lookup</span> <span class="attr">id</span>=<span class="string">"dataSource"</span> <span class="attr">jndi-name</span>=<span class="string">"jdbc/jpetstore"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"txManager"</span> <span class="attr">class</span>=<span class="string">"org.springframework.transaction.jta.JtaTransactionManager"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- other &lt;bean/&gt; definitions here --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>​    </p>
<h3 id="和-JPA-Hibernate-的集成"><a href="#和-JPA-Hibernate-的集成" class="headerlink" title="和 JPA/Hibernate 的集成"></a>和 JPA/Hibernate 的集成</h3><p>​    注意不要眼花了，上节说的是<strong>JTA</strong>，这一节讲述的是ORM相关的JPA，关于他们的概念这里不再赘述，如果你的数据库使用的是JPA，使用声明式事务可以避免一个比较核心的问题，下面是代码的案例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> SessionFactory sessionFactory; <span class="comment">// (1)</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerUser</span><span class="params">(User user)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 开启连接</span></span><br><span class="line">        Session session = sessionFactory.openSession(); <span class="comment">// (2)</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 开启一个JPA的事务</span></span><br><span class="line">        session.beginTransaction();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 执行一个insert操作</span></span><br><span class="line">        session.save(user);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 提交事务</span></span><br><span class="line">        session.getTransaction().commit();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 关闭连接</span></span><br><span class="line">        session.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    这样的代码会出现下面两个严重的问题：</p>
<ul>
<li>Hibernate 不知道 Spring 的 <code>@Transactional</code> 注释。</li>
<li>Spring 的 <code>@Transactional</code>对 Hibernate 的事务一无所知。</li>
</ul>
<p>​    如果我们使用声明式事务就不会出现上面的情况，Spring会在事务启动的时候，会自动切换到<span class="exturl" data-url="aHR0cHM6Ly9kb2NzLnNwcmluZy5pby9zcHJpbmctZnJhbWV3b3JrL2RvY3MvY3VycmVudC9qYXZhZG9jLWFwaS9vcmcvc3ByaW5nZnJhbWV3b3JrL29ybS9oaWJlcm5hdGU1L0hpYmVybmF0ZVRyYW5zYWN0aW9uTWFuYWdlci5odG1s" title="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/orm/hibernate5/HibernateTransactionManager.html">HibernateTransactionManager<i class="fa fa-external-link"></i></span> 或<span class="exturl" data-url="aHR0cHM6Ly9kb2NzLnNwcmluZy5pby9zcHJpbmctZnJhbWV3b3JrL2RvY3MvY3VycmVudC9qYXZhZG9jLWFwaS9vcmcvc3ByaW5nZnJhbWV3b3JrL29ybS9qcGEvSnBhVHJhbnNhY3Rpb25NYW5hZ2VyLmh0bWw=" title="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/orm/jpa/JpaTransactionManager.html">JpaTransactionManager<i class="fa fa-external-link"></i></span>（如果通过 JPA使用 Hibernate），HibernateTransactionManager 会确保这两种会话形式合并为同一个，这里也体现了一个非常常见的适配器模式的思路。</p>
<h3 id="响应式事务"><a href="#响应式事务" class="headerlink" title="响应式事务"></a>响应式事务</h3><p>​    响应式事务目前依然属于一个比较新颖的东西，也是Spring的未来主攻方向，极限编程的思想比较有意思，但是从目前环境来看使用频率比较低，所以此文就不再进行扩展讲述。</p>
<blockquote>
<p>还有更多的集成和使用方式可以参阅官方的文档，文章篇幅有限不能面面俱到。</p>
</blockquote>
<h2 id="（2）配置方式-1"><a href="#（2）配置方式-1" class="headerlink" title="（2）配置方式"></a>（2）配置方式</h2><p>​    声明式事务的配置方式有四种，其中最常使用的是注解的方式进行事务处理。</p>
<ol>
<li><strong>TransactionInterceptor</strong>  ：使用TransactionInterceptor 拦截器的方式，这种方式虽然不推荐使用，但是对于理解spring事务是有一定帮助的，感兴趣可以阅读一下这个类。</li>
<li><strong>基于AspectJ的XML方式</strong>（&lt;tx&gt;和&lt;aop&gt;标签）：不需要改动类，在XML文件中配置好即可，比如下面提供了一个事务的配置模板，同样是基于切面aop进行拦截增加事务的。</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 事务管理器 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"transactionManager"</span></span></span><br><span class="line"><span class="tag">	<span class="attr">class</span>=<span class="string">"org.springframework.jdbc.datasource.DataSourceTransactionManager"</span>&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 数据源 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"dataSource"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">tx:annotation-driven</span> <span class="attr">transaction-manager</span>=<span class="string">"transactionManager"</span> /&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 通知 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">tx:advice</span> <span class="attr">id</span>=<span class="string">"txAdvice"</span> <span class="attr">transaction-manager</span>=<span class="string">"transactionManager"</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">tx:attributes</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 传播行为 --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"save*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span> /&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"insert*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span> /&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"delete*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span> /&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"update*"</span> <span class="attr">propagation</span>=<span class="string">"REQUIRED"</span> /&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"find*"</span> <span class="attr">propagation</span>=<span class="string">"SUPPORTS"</span> <span class="attr">read-only</span>=<span class="string">"true"</span> /&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">tx:method</span> <span class="attr">name</span>=<span class="string">"get*"</span> <span class="attr">propagation</span>=<span class="string">"SUPPORTS"</span> <span class="attr">read-only</span>=<span class="string">"true"</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">tx:attributes</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">tx:advice</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 切面 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">aop:config</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">aop:advisor</span> <span class="attr">advice-ref</span>=<span class="string">"txAdvice"</span></span></span><br><span class="line"><span class="tag">		<span class="attr">pointcut</span>=<span class="string">"execution(* service.*.*(..))"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">aop:config</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li><strong>基于事务代理工厂的Bean进行配置</strong>：比如下面配置了一个代理工厂的Bean - <strong>TransactionProxyFactoryBean</strong>，这种方式在以前是Spring推荐的方式，配置方式也比较古老，并且早在Spring2.0就不推荐使用了。</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">  .....</span><br><span class="line">      </span><br><span class="line">    <span class="comment">&lt;!-- 事务管理器 --&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"myTracnsactionManager"</span> <span class="attr">class</span>=<span class="string">"org.springframework.jdbc.datasource.DataSourceTransactionManager"</span>&gt;</span>  </span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dataSource"</span> <span class="attr">ref</span>=<span class="string">"dataSource"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span>  </span><br><span class="line">      </span><br><span class="line">    <span class="comment">&lt;!-- 事务代理工厂 --&gt;</span>  </span><br><span class="line">    <span class="comment">&lt;!-- 生成事务代理对象 --&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"serviceProxy"</span> <span class="attr">class</span>=<span class="string">"org.springframework.transaction.interceptor.TransactionProxyFactoryBean"</span>&gt;</span>  </span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"transactionManager"</span> <span class="attr">ref</span>=<span class="string">"myTracnsactionManager"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span>  </span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"target"</span> <span class="attr">ref</span>=<span class="string">"buyStockService"</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span>  </span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"transactionAttributes"</span>&gt;</span>  </span><br><span class="line">            <span class="tag">&lt;<span class="name">props</span>&gt;</span>  </span><br><span class="line">                <span class="comment">&lt;!-- 主要 key 是方法     </span></span><br><span class="line"><span class="comment">                    ISOLATION_DEFAULT  事务的隔离级别  </span></span><br><span class="line"><span class="comment">                    PROPAGATION_REQUIRED  传播行为  </span></span><br><span class="line"><span class="comment">                --&gt;</span>  </span><br><span class="line">                <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"add*"</span>&gt;</span>ISOLATION_DEFAULT,PROPAGATION_REQUIRED<span class="tag">&lt;/<span class="name">prop</span>&gt;</span>  </span><br><span class="line">                <span class="comment">&lt;!-- -Exception 表示发生指定异常回滚，+Exception 表示发生指定异常提交 --&gt;</span>  </span><br><span class="line">                <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"buyStock"</span>&gt;</span>ISOLATION_DEFAULT,PROPAGATION_REQUIRED,-BuyStockException<span class="tag">&lt;/<span class="name">prop</span>&gt;</span>  </span><br><span class="line">            <span class="tag">&lt;/<span class="name">props</span>&gt;</span>  </span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span>  </span><br><span class="line">          </span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span> </span><br><span class="line">.....</span><br></pre></td></tr></table></figure>

<ol start="4">
<li>最后就是常见<strong>使用@Transactional注解的方式进行配置</strong>，如果SpringBoot可以配合<code>@EnableTransactionManagement</code>直接引入事务，@Transactional可以配置在某个类上，也可以配置在方法上，但是同样依赖AOP同时只支持方法级的事务控制而不支持代码块级的事务控制。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Transactional</span>(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,rollbackFor=BuyStockException<span class="class">.<span class="keyword">class</span>)</span></span><br></pre></td></tr></table></figure>



<h2 id="（3）理解事务传播级别"><a href="#（3）理解事务传播级别" class="headerlink" title="（3）理解事务传播级别"></a>（3）理解事务传播级别</h2><p>​    在上文我们提到了通过事务属性对象TransactionDefinition 进行事务的传播机制判断，这里我们接着来看一下事务的传播机制的类型，事务的传播级别在前文已经提到过了这里我们再回顾一下：</p>
<table>
<thead>
<tr>
<th>特点</th>
<th>传播级别</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_REQUIRED</td>
<td>如果当前存在事务，则加入该事务；如果当前没有事务，则创建一个新的事务。</td>
</tr>
<tr>
<td>支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_SUPPORTS</td>
<td>如果当前存在事务，则加入该事务；如果当前没有事务，则以非事务的方式继续运行。</td>
</tr>
<tr>
<td>支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_MANDATORY</td>
<td>如果当前存在事务，则加入该事务；如果当前没有事务，则抛出异常。（mandatory：强制性）</td>
</tr>
<tr>
<td>不支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_REQUIRES_NEW</td>
<td>创建一个新的事务，如果当前存在事务，则把当前事务挂起。</td>
</tr>
<tr>
<td>不支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_NOT_SUPPORTED</td>
<td>以非事务方式运行，如果当前存在事务，则把当前事务挂起。</td>
</tr>
<tr>
<td>不支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_NEVER</td>
<td>以非事务方式运行，如果当前存在事务，则抛出异常。</td>
</tr>
<tr>
<td>其他情况</td>
<td>TransactionDefinition.PROPAGATION_NESTED</td>
<td>如果当前存在事务，则创建一个事务作为当前事务的嵌套事务来运行；如果当前没有事务，则该取值等价于TransactionDefinition.PROPAGATION_REQUIRED。</td>
</tr>
</tbody></table>
<p>​    <strong>理解 <code>PROPAGATION_REQUIRED</code>：</strong></p>
<p>​    PROPAGATION_REQUIRED 如果不存在事务，就新建事务，如果出现嵌套的事务就会参与外层的事务而不会再新建。 这是同一线程内公共调用的十分方便的默认设置（例如委托给多个存储库方法的服务外观，其中所有底层资源都必须参与服务级别事务），同时基本能对付绝大多数的业务系统。</p>
<blockquote>
<p>讨论：这里讨论一下Spring官方文档和源码说明的“冲突”，默认情况下，如果出现嵌套事务，会默认采用已有事务，这样针对内部新建的事务会默认<strong>忽略事务隔离级别、超时值或只读标志（如果有）</strong>。 如果希望在内部事务采用不同隔离级别时候被外部事务拒绝并且抛出异常，可以考虑将事务管理器上的 <strong>validateExistingTransactions</strong> 标志切换为 true。</p>
<p>​    其实这种说法和源代码来看其实不是特别吻合，实际上如果设置validateExistingTransactions为false，会发现事务将继续执行，即使隔离级别与请求的不同，会按照外部事务的优先级执行，这样其实就导致了事务配置只看一份文件的情况，具体可以参考下面这一段代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (isValidateExistingTransaction()) &#123;</span><br><span class="line">			<span class="keyword">if</span> (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) &#123;</span><br><span class="line">				I</span><br><span class="line">			&#125;</span><br><span class="line">  	<span class="comment">// 如果设置了只读但是当前事务没有只读，则抛出异常</span></span><br><span class="line">			<span class="keyword">if</span> (!definition.isReadOnly()) &#123;</span><br><span class="line">				<span class="keyword">if</span> (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) &#123;</span><br><span class="line">					<span class="keyword">throw</span> <span class="keyword">new</span> IllegalTransactionStateException(<span class="string">"Participating transaction with definition ["</span> +</span><br><span class="line">							definition + <span class="string">"] is not marked as read-only but existing transaction is"</span>);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 没有则同步构建一个空事务</span></span><br></pre></td></tr></table></figure>
</blockquote>
<p>​    最后再补一张官方的图：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211230171527.png" alt=""></p>
<p>​    </p>
<p>​    <strong>理解 <code>PROPAGATION_REQUIRES_NEW</code>：</strong></p>
<p>​    <code>PROPAGATION_REQUIRES_NEW</code>与 相比<code>PROPAGATION_REQUIRED</code>，<strong>始终为每个受影响的事务范围使用独立的事务</strong>，从不参与外部范围的现有事务。每一个事务资源都是独立的，因此可以独立提交或回滚，外部事务同样不受内部事务回滚状态的影响，内部事务的锁在完成后立即释放。这样一个独立的内部事务也可以声明自己的隔离级别、超时和只读设置，<strong>而不继承外部事务的特性</strong>。</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211230171507.png" alt=""></p>
<p>​    </p>
<p>​    <strong>理解 <code>PROPAGATION_NESTED</code>：</strong></p>
<p>​    <code>PROPAGATION_NESTED</code>使用了保存点的方式。嵌套事务意味着可以实现部分事务的回滚，但是嵌套的内部事务不会影响外部事务的执行。<strong>注意这个设置仅适用于 JDBC 资源事务</strong>，源码里面也有解释，可以参阅 Spring 的<a href="https://docs.spring.io/spring-framework/docs/5.3.14/javadoc-api/org/springframework/jdbc/datasource/DataSourceTransactionManager.html" target="_blank" rel="noopener"><code>DataSourceTransactionManager</code></a>。</p>
<h2 id="（3）源码解析"><a href="#（3）源码解析" class="headerlink" title="（3）源码解析"></a>（3）源码解析</h2><p>​    声明式事务要比编程式事务复杂不少，这一部分的代码不会深入讲解AOP的部分，同时由于使用了SpringBoot自动注入的特性这里也尽量不过度深入讲述，下面我们从两个部分来分析声明式式的内部操作流程：</p>
<ol>
<li>自动配置注入</li>
<li>注解拦截解析</li>
</ol>
<h3 id="自动配置注入"><a href="#自动配置注入" class="headerlink" title="自动配置注入"></a>自动配置注入</h3><p>​    首先来啃啃第一块大骨头。我们先从一个SpringApplication的注解开始开始，上文提到过SpringBoot新版本中如果碰到事务的相关依赖，会自动接入Spring的事务控制，我们可以通过注解@EnableTransaction进行排查，发现内部存在一个@EnableAutoConfiguration，Spring启动的时候，会扫描源代码包根路径下面一个叫做<code>spring.factories</code>的文件，在大约127行位置有一个<code>org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration</code>的配置，在这个配置下面中有一个<code>TransactionAutoConfiguration</code>的配置，当容器启动的时候会自动根据配置扫描相关的包载入相关的bean。最后从事务自动注入的注解内，可以从下面的截图看到一些熟悉的影子，这里不再重复解释。</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211231151719.png" alt=""></p>
<p>​    接着我们再回过头看一下@EnableTransaction注解内部的内容，这里使用了@Import注入了TransactionManagementConfigurationSelector，这个类的作用是根据导入 @Configuration 类上的 EnableTransactionManagement.mode() 的值选择应使用 AbstractTransactionManagementConfiguration 的哪个实现。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Import</span>(TransactionManagementConfigurationSelector<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class"><span class="title">public</span> @<span class="title">interface</span> <span class="title">EnableTransactionManagement</span></span></span><br></pre></td></tr></table></figure>

<p>​    我们可以从下面的代码看到，这里提供了两种代理方式，一种是根据JDK的代理模式，另一种是根据AspectJ的代理默认，Spring在默认情况下会优先选择JDK的代理，如果没有才会选择AspectJ的代理（总觉得Spring作者对于Aop总有一种遗憾和执念），如果读者想知道在哪里配置的，可以看看<code>org.springframework.scheduling.annotation.EnableAsync#mode</code>中存在一个默认的JDK代理配置，在下面的代码中可以到走JDK的代理注入了两个类<code>AutoProxyRegistrar.class</code>和<code>ProxyTransactionManagementConfiguration.class</code> 。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">AdviceMode <span class="title">mode</span><span class="params">()</span> <span class="keyword">default</span> AdviceMode.PROXY</span>;</span><br><span class="line"></span><br><span class="line">-----分割线----</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">	根据选择的代理模式生成不同的代理器</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line">	<span class="keyword">protected</span> String[] selectImports(AdviceMode adviceMode) &#123;</span><br><span class="line">		<span class="keyword">switch</span> (adviceMode) &#123;</span><br><span class="line">        <span class="comment">// 默认都会走JDK的代理</span></span><br><span class="line">			<span class="keyword">case</span> PROXY:</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> String[] &#123;AutoProxyRegistrar<span class="class">.<span class="keyword">class</span>.<span class="title">getName</span>(),</span></span><br><span class="line"><span class="class">						<span class="title">ProxyTransactionManagementConfiguration</span>.<span class="title">class</span>.<span class="title">getName</span>()&#125;</span>;</span><br><span class="line">        <span class="comment">// 如果选择ApectJ，可以参考下面的代码</span></span><br><span class="line">			<span class="keyword">case</span> ASPECTJ:</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">new</span> String[] &#123;determineTransactionAspectClass()&#125;;</span><br><span class="line">			<span class="keyword">default</span>:</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<p><code>AutoProxyRegistrar.class</code>：</p>
<p>​    这个类直译就是自动代理注册器，它是一个后置处理器，负责给容器中注册一个InfrastructureAdvisorAutoProxyCreator，InfrastructureAdvisorAutoProxyCreator，利用后置处理器机制在对象创建以后，对对象进行包装，返回一个代理对象(增强器)，代理对象执行方法，利用拦截器链进行调用，下面是关于注册器的部分代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">boolean</span> candidateFound = <span class="keyword">false</span>;</span><br><span class="line">		Set&lt;String&gt; annTypes = importingClassMetadata.getAnnotationTypes();</span><br><span class="line">		<span class="keyword">for</span> (String annType : annTypes) &#123;</span><br><span class="line">      <span class="comment">// 解析和获取注解信息</span></span><br><span class="line">			AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);</span><br><span class="line">			<span class="keyword">if</span> (candidate == <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">continue</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			Object mode = candidate.get(<span class="string">"mode"</span>);</span><br><span class="line">			Object proxyTargetClass = candidate.get(<span class="string">"proxyTargetClass"</span>);</span><br><span class="line">			<span class="keyword">if</span> (mode != <span class="keyword">null</span> &amp;&amp; proxyTargetClass != <span class="keyword">null</span> &amp;&amp; AdviceMode<span class="class">.<span class="keyword">class</span> </span>== mode.getClass() &amp;&amp;</span><br><span class="line">					Boolean<span class="class">.<span class="keyword">class</span> </span>== proxyTargetClass.getClass()) &#123;</span><br><span class="line">        <span class="comment">// 校验是否设置开启代理，如果配置则查看是否为JDK代理</span></span><br><span class="line">				candidateFound = <span class="keyword">true</span>;</span><br><span class="line">				<span class="keyword">if</span> (mode == AdviceMode.PROXY) &#123;</span><br><span class="line">          <span class="comment">// 核心代码，如果有必要就创建一个自动代理创建器</span></span><br><span class="line">					AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);</span><br><span class="line">					<span class="keyword">if</span> ((Boolean) proxyTargetClass) &#123;</span><br><span class="line">            <span class="comment">// 强制将自动代理创建器绑定到用户代理</span></span><br><span class="line">						AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);</span><br><span class="line">						<span class="keyword">return</span>;</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">//......</span></span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<p>​    接着进入方法<code>AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);</code>的内部实现<code>org.springframework.aop.config.AopConfigUtils#registerOrEscalateApcAsRequired</code>方法，AopConfigUtils这个工具类为AOP动态代理类创建器的主要负责工具：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Nullable</span></span><br><span class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">static</span> BeanDefinition <span class="title">registerOrEscalateApcAsRequired</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">			Class&lt;?&gt; cls, BeanDefinitionRegistry registry, @Nullable Object source)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 断言是否存在Bean，BeanDefinitionRegistry就是Spring容器中Bean的实际存在形式</span></span><br><span class="line">		Assert.notNull(registry, <span class="string">"BeanDefinitionRegistry must not be null"</span>);</span><br><span class="line">		<span class="comment">// 注册器先判断是否有注入org.springframework.aop.config.internalAutoProxyCreator</span></span><br><span class="line">		<span class="keyword">if</span> (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) &#123;</span><br><span class="line">			BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);</span><br><span class="line">			<span class="keyword">if</span> (!cls.getName().equals(apcDefinition.getBeanClassName())) &#123;</span><br><span class="line">        <span class="comment">// 这里根据优先级获取，第一次进来的时候是肯定没有注入的</span></span><br><span class="line">				<span class="keyword">int</span> currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());</span><br><span class="line">				<span class="keyword">int</span> requiredPriority = findPriorityForClass(cls);</span><br><span class="line">				<span class="keyword">if</span> (currentPriority &lt; requiredPriority) &#123;</span><br><span class="line">					apcDefinition.setBeanClassName(cls.getName());</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 可以看作是将InfrastructureAdvisorAutoProxyCreator包装成RootBeanDefinition</span></span><br><span class="line">		RootBeanDefinition beanDefinition = <span class="keyword">new</span> RootBeanDefinition(cls);</span><br><span class="line">		beanDefinition.setSource(source);</span><br><span class="line">		beanDefinition.getPropertyValues().add(<span class="string">"order"</span>, Ordered.HIGHEST_PRECEDENCE);</span><br><span class="line">		beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);</span><br><span class="line">    <span class="comment">// 核心部分：注入bean到ioc到容器当中，名字就是 org.springframework.aop.config.internalAutoProxyCreator</span></span><br><span class="line">		registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);</span><br><span class="line">		<span class="keyword">return</span> beanDefinition;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<p>​    我们知道了InfrastructureAdvisorAutoProxyCreator这个类是如何集成到IOC容器之后，发现这个类属于一个下属的实现子类，我们通过继承链向上找到父类：AbstractAutoProxyCreator，这个类名字翻译过来是<strong>抽象自动代理创建器</strong>，他的作用是如果 bean 被子类标识为代理，则使用配置的拦截器创建代理，这里可以看作代理的生产者和执行者之间的解耦，核心代码如下部分：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20220102161325.png" alt=""></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(@Nullable Object bean, String beanName)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (bean != <span class="keyword">null</span>) &#123;</span><br><span class="line">			Object cacheKey = getCacheKey(bean.getClass(), beanName);</span><br><span class="line">			<span class="keyword">if</span> (<span class="keyword">this</span>.earlyProxyReferences.remove(cacheKey) != bean) &#123;</span><br><span class="line">        <span class="comment">// 是否必要进行增强包装处理</span></span><br><span class="line">				<span class="keyword">return</span> wrapIfNecessary(bean, beanName, cacheKey);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> bean;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>

<p>​    内部的代码逻辑就不过多展开了，总结InfrastructureAdvisorAutoProxyCreator作用就是：<strong>利用后置处理器机制在对象创建以后，对对象进行包装，返回一个代理对象(增强器)，代理对象执行方法，最后利用拦截器链进行调用。</strong></p>
<blockquote>
<p>Tips：这部分代码需要对于Spring IOC和AOP的实现底层掌握比较牢固才能彻底理解，建议阅读卡死之后不要死犟，可以补补其他的模块实现之后再来啃下事务是如何集成到IOC和AOP的。</p>
</blockquote>
<h3 id="注解拦截解析"><a href="#注解拦截解析" class="headerlink" title="注解拦截解析"></a>注解拦截解析</h3><p>​    我们大致了解了自动配置自动配置是如何注入到Spring IOC之后，我们接着来看下Spring是如何实现事务的注解拦截解析的，也就是@Transactional注解的解析过程，上文说过，注解拦截器调用这里不再啰嗦，这里回到前文的对象<code>ProxyTransactionManagementConfiguration</code>也就是代理配置管理器开始，这里读者可能有疑问这个类那里突然冒出来的，这里给个提示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">case</span> PROXY:</span><br><span class="line"><span class="keyword">return</span> <span class="keyword">new</span> String[] &#123;AutoProxyRegistrar<span class="class">.<span class="keyword">class</span>.<span class="title">getName</span>(),</span></span><br><span class="line"><span class="class">                     <span class="title">ProxyTransactionManagementConfiguration</span>.<span class="title">class</span>.<span class="title">getName</span>()&#125;</span>;</span><br></pre></td></tr></table></figure>

<p>​    下面截取了部分代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span>(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)</span><br><span class="line"><span class="meta">@Role</span>(BeanDefinition.ROLE_INFRASTRUCTURE)</span><br><span class="line"><span class="function"><span class="keyword">public</span> BeanFactoryTransactionAttributeSourceAdvisor <span class="title">transactionAdvisor</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">  TransactionAttributeSource transactionAttributeSource, TransactionInterceptor transactionInterceptor)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  BeanFactoryTransactionAttributeSourceAdvisor advisor = <span class="keyword">new</span> BeanFactoryTransactionAttributeSourceAdvisor();</span><br><span class="line">  <span class="comment">// 向切面中注入注解解析器,专门来解析事务注解的</span></span><br><span class="line">  advisor.setTransactionAttributeSource(transactionAttributeSource);</span><br><span class="line">  <span class="comment">// 向切面中注入事务的拦截器,专门来拦截方法,包括事务的提交以及回滚操作</span></span><br><span class="line">  advisor.setAdvice(transactionInterceptor);</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">this</span>.enableTx != <span class="keyword">null</span>) &#123;</span><br><span class="line">    advisor.setOrder(<span class="keyword">this</span>.enableTx.&lt;Integer&gt;getNumber(<span class="string">"order"</span>));</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> advisor;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    接着我们看一下被注入的属性：<code>TransactionAttributeSource</code>，这个类用于处理注解的属性和相关内容，也是注解解析器，这个类拥有很多的实现子类，因为是注解解析器，这里我们直接看：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20220102163759.png" alt=""></p>
<p>​    部分代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AnnotationTransactionAttributeSource</span><span class="params">(<span class="keyword">boolean</span> publicMethodsOnly)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.publicMethodsOnly = publicMethodsOnly;</span><br><span class="line">		<span class="keyword">if</span> (jta12Present || ejb3Present) &#123;</span><br><span class="line">			<span class="keyword">this</span>.annotationParsers = <span class="keyword">new</span> LinkedHashSet&lt;&gt;(<span class="number">4</span>);</span><br><span class="line">      <span class="comment">// spring注解解析器</span></span><br><span class="line">			<span class="keyword">this</span>.annotationParsers.add(<span class="keyword">new</span> SpringTransactionAnnotationParser());</span><br><span class="line">			<span class="keyword">if</span> (jta12Present) &#123;</span><br><span class="line">        <span class="comment">// jta解析起</span></span><br><span class="line">				<span class="keyword">this</span>.annotationParsers.add(<span class="keyword">new</span> JtaTransactionAnnotationParser());</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">if</span> (ejb3Present) &#123;</span><br><span class="line">        <span class="comment">// ejb3的解析器</span></span><br><span class="line">				<span class="keyword">this</span>.annotationParsers.add(<span class="keyword">new</span> Ejb3TransactionAnnotationParser());</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 使用spring注解解析器</span></span><br><span class="line">			<span class="keyword">this</span>.annotationParsers = Collections.singleton(<span class="keyword">new</span> SpringTransactionAnnotationParser());</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//调用org.springframework.transaction.annotation.SpringTransactionAnnotationParser#parseTransactionAnnotation方法，内部部分代码如下：</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringTransactionAnnotationParser</span> <span class="keyword">implements</span> <span class="title">TransactionAnnotationParser</span>, <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">protected</span> TransactionAttribute <span class="title">parseTransactionAnnotation</span><span class="params">(AnnotationAttributes attributes)</span> </span>&#123;</span><br><span class="line">		RuleBasedTransactionAttribute rbta = <span class="keyword">new</span> RuleBasedTransactionAttribute();</span><br><span class="line"></span><br><span class="line">		Propagation propagation = attributes.getEnum(<span class="string">"propagation"</span>);</span><br><span class="line">		rbta.setPropagationBehavior(propagation.value());</span><br><span class="line">		Isolation isolation = attributes.getEnum(<span class="string">"isolation"</span>);</span><br><span class="line">		rbta.setIsolationLevel(isolation.value());</span><br><span class="line">		rbta.setTimeout(attributes.getNumber(<span class="string">"timeout"</span>).intValue());</span><br><span class="line">		rbta.setReadOnly(attributes.getBoolean(<span class="string">"readOnly"</span>));</span><br><span class="line">		rbta.setQualifier(attributes.getString(<span class="string">"value"</span>));</span><br><span class="line"></span><br><span class="line">		List&lt;RollbackRuleAttribute&gt; rollbackRules = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">		<span class="keyword">for</span> (Class&lt;?&gt; rbRule : attributes.getClassArray(<span class="string">"rollbackFor"</span>)) &#123;</span><br><span class="line">			rollbackRules.add(<span class="keyword">new</span> RollbackRuleAttribute(rbRule));</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">for</span> (String rbRule : attributes.getStringArray(<span class="string">"rollbackForClassName"</span>)) &#123;</span><br><span class="line">			rollbackRules.add(<span class="keyword">new</span> RollbackRuleAttribute(rbRule));</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">for</span> (Class&lt;?&gt; rbRule : attributes.getClassArray(<span class="string">"noRollbackFor"</span>)) &#123;</span><br><span class="line">			rollbackRules.add(<span class="keyword">new</span> NoRollbackRuleAttribute(rbRule));</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">for</span> (String rbRule : attributes.getStringArray(<span class="string">"noRollbackForClassName"</span>)) &#123;</span><br><span class="line">			rollbackRules.add(<span class="keyword">new</span> NoRollbackRuleAttribute(rbRule));</span><br><span class="line">		&#125;</span><br><span class="line">		rbta.setRollbackRules(rollbackRules);</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> rbta;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    上面的代码比较好理解，就是对于注解的内部进行解析和封装。接着我们看一下是拦截器TransactionAspectSupport，这个拦截器实现了MethodInterceptor接口，标志为他是一个方法的拦截器，核心方法是内部的invoke()方法。</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20211227223244.png" alt=""></p>
<p>​    内部的invoke()方法内容如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(MethodInvocation invocation)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">   <span class="comment">// 计算出目标类：可能是&#123;@code null&#125;。 TransactionAttributeSource 应该传递目标类以及方法，这可能来自接口。</span></span><br><span class="line">   Class&lt;?&gt; targetClass = (invocation.getThis() != <span class="keyword">null</span> ? AopUtils.getTargetClass(invocation.getThis()) : <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// 适配方法执行</span></span><br><span class="line">   <span class="keyword">return</span> invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    接着进入核心的适配方法<code>invokeWithinTransaction</code>，代码比较多，这里截取部分代码介绍：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Nullable</span></span><br><span class="line">	<span class="function"><span class="keyword">protected</span> Object <span class="title">invokeWithinTransaction</span><span class="params">(Method method, @Nullable Class&lt;?&gt; targetClass,</span></span></span><br><span class="line"><span class="function"><span class="params">			<span class="keyword">final</span> InvocationCallback invocation)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 如果事务属性为空，则该方法是非事务性的（就是非事务方式执行）</span></span><br><span class="line">		TransactionAttributeSource tas = getTransactionAttributeSource();</span><br><span class="line">		<span class="keyword">final</span> TransactionAttribute txAttr = (tas != <span class="keyword">null</span> ? tas.getTransactionAttribute(method, targetClass) : <span class="keyword">null</span>);</span><br><span class="line">		<span class="keyword">final</span> TransactionManager tm = determineTransactionManager(txAttr);</span><br><span class="line">		<span class="comment">// 如果当前的注册器是响应式的，则按照响应式的方式处理</span></span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">this</span>.reactiveAdapterRegistry != <span class="keyword">null</span> &amp;&amp; tm <span class="keyword">instanceof</span> ReactiveTransactionManager) &#123;</span><br><span class="line">			<span class="comment">// .......</span></span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		PlatformTransactionManager ptm = asPlatformTransactionManager(tm);</span><br><span class="line">		<span class="keyword">final</span> String joinpointIdentification = methodIdentification(method, targetClass, txAttr);</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span> (txAttr == <span class="keyword">null</span> || !(ptm <span class="keyword">instanceof</span> CallbackPreferringPlatformTransactionManager)) &#123;</span><br><span class="line">			<span class="comment">// 使用 getTransaction 和 commit/rollback 调用进行事务划分。</span></span><br><span class="line">			TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);</span><br><span class="line"></span><br><span class="line">			Object retVal;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">				<span class="comment">// 这是环绕通知，调用拦截链中的下一个拦截器。 实际会调用目标对象。</span></span><br><span class="line">				retVal = invocation.proceedWithInvocation();</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">				<span class="comment">// 目标方法调用失败</span></span><br><span class="line">				completeTransactionAfterThrowing(txInfo, ex);</span><br><span class="line">				<span class="keyword">throw</span> ex;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">// 事务的后续清理操作</span></span><br><span class="line">				cleanupTransactionInfo(txInfo);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="comment">// </span></span><br><span class="line">			<span class="keyword">if</span> (retVal != <span class="keyword">null</span> &amp;&amp; vavrPresent &amp;&amp; VavrDelegate.isVavrTry(retVal)) &#123;</span><br><span class="line">				<span class="comment">// 如果符合回滚规则则进行回滚</span></span><br><span class="line">				TransactionStatus status = txInfo.getTransactionStatus();</span><br><span class="line">				<span class="keyword">if</span> (status != <span class="keyword">null</span> &amp;&amp; txAttr != <span class="keyword">null</span>) &#123;</span><br><span class="line">					retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="comment">// 未出现异常,也获取事务管理器则进行事务的提交</span></span><br><span class="line">			commitTransactionAfterReturning(txInfo);</span><br><span class="line">			<span class="keyword">return</span> retVal;</span><br><span class="line">		&#125;</span><br><span class="line">	<span class="comment">// .......</span></span><br></pre></td></tr></table></figure>

<p>​    </p>
<h1 id="六、Spring事务实战"><a href="#六、Spring事务实战" class="headerlink" title="六、Spring事务实战"></a>六、Spring事务实战</h1><h2 id="（1）介绍"><a href="#（1）介绍" class="headerlink" title="（1）介绍"></a>（1）介绍</h2><p>​    为了防止读者误解，这里提前介绍一下本次实验操作的Spring版本和数据库版本：</p>
<ul>
<li>spring-boot：5.2.8</li>
<li>mysql：5.7</li>
</ul>
<p>下面我们进入实际部分，实战部分主要针对事务比较常见的使用：</p>
<ul>
<li>事务不生效的一些“坑”，以及如何规避或者如何解决。</li>
<li>不同事务的传播机制在实际代码中的效果。</li>
<li>大事务的问题，以及相关的处理方法。</li>
</ul>
<h2 id="（2）事务不生效的一些坑"><a href="#（2）事务不生效的一些坑" class="headerlink" title="（2）事务不生效的一些坑"></a>（2）事务不生效的一些坑</h2><p>​    首先来看一下事务不生效的一些坑，同样我们一开始需要构建一张表作为测试：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`t_trans_test`</span> (</span><br><span class="line">  <span class="string">`id`</span> <span class="built_in">int</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT,</span><br><span class="line">  <span class="string">`name`</span> <span class="built_in">varchar</span>(<span class="number">255</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  <span class="string">`amount`</span> <span class="built_in">decimal</span>(<span class="number">16</span>,<span class="number">0</span>) <span class="keyword">DEFAULT</span> <span class="literal">NULL</span>,</span><br><span class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>)</span><br><span class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8mb3;</span><br></pre></td></tr></table></figure>

<p>​    这里构建两条数据，分别表示两个人的余额：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="string">`transaction_tb`</span>.<span class="string">`t_trans_test`</span> (<span class="string">`id`</span>, <span class="string">`name`</span>, <span class="string">`amount`</span>) <span class="keyword">VALUES</span> (<span class="number">1</span>, <span class="string">'用户A'</span>, <span class="number">1000</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="string">`transaction_tb`</span>.<span class="string">`t_trans_test`</span> (<span class="string">`id`</span>, <span class="string">`name`</span>, <span class="string">`amount`</span>) <span class="keyword">VALUES</span> (<span class="number">2</span>, <span class="string">'用户B'</span>, <span class="number">500</span>);</span><br></pre></td></tr></table></figure>



<h3 id="1-非事务方法调用事务方法"><a href="#1-非事务方法调用事务方法" class="headerlink" title="1.  非事务方法调用事务方法"></a>1.  非事务方法调用事务方法</h3><p>​    如果在一个非事务的方法内部调用一个事务的方法，无论是否加注解，会发现抛出异常的时候会事务不回滚的情况，也是最常见的情况，如下代码所描述的，假设我们用A给B转钱，A-100和B+100，如果在B中加入事务注解，但是A没有加，则会发现A的操作是没有回滚的：</p>
<blockquote>
<p>提示：这样的操作仅作演示，工作中扣款和充值绝对不是这样操作的。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 随机异常触发flag</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> EXCEPTIN_FLAG = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> JdbcTemplate jdbcTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 事务失效的第一种情况：非事务方法调用事务方法</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">		<span class="comment">// 放开下面的注解即正常</span></span><br><span class="line">		<span class="comment">// @Transactional(rollbackFor = Exception.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">nonTransactionUseTrasaction</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"发起转账"</span>);</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-100 where name='用户A'"</span>);</span><br><span class="line">        innerMethod();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">public</span> <span class="title">void</span> <span class="title">innerMethod</span>()</span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"接受转账"</span>);</span><br><span class="line">        <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"转账失败"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount+100 where name='用户B'"</span>);</span><br><span class="line">    &#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">    =========== 运行前数据准备重置数据 ========</span></span><br><span class="line"><span class="comment">    发起转账</span></span><br><span class="line"><span class="comment">    接受转账</span></span><br><span class="line"><span class="comment">    ====== 运行后查询操作结果 ======</span></span><br><span class="line"><span class="comment">    &#123;id=1, name=用户A, amount=900&#125;</span></span><br><span class="line"><span class="comment">    &#123;id=2, name=用户B, amount=500&#125;</span></span><br><span class="line"><span class="comment">    */</span></span><br></pre></td></tr></table></figure>

<p>​    解决方式：</p>
<p>​    解决方式有两种，一种是我们在事务A的上面增加一个回滚的注解，这个无需过多解释，但是如果有时候我们想让事务在一个内部的方法里面让事务的范围锁定在想要的方法。</p>
<p>最常见的一种方式是“注入自己”，还有一种方式是<strong>先允许获取Spring的代理对象，然后通过获取Spring的代理对象完成操作</strong>。</p>
<p>此外在spring5.0之后的版本又增加了新的获取方式，比如spring-test有<code>AopTestUtils</code>来获取，下面我们汇总一下这些方法，如果读者感兴趣可以实际验证一遍：</p>
<ul>
<li>注入“自己”。丑陋又笨，但是又快又有效。</li>
<li>使用`AopContext.currentProxy()``。</li>
<li>注入<code>ApplicationContext</code>，获取代理对象。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">//    @Transactional(rollbackFor = Exception.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">nonTransactionUseTrasaction</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"发起转账"</span>);</span><br><span class="line"><span class="comment">//        jdbcTemplate.update("update t_trans_test set amount=amount-100 where name='用户A'");</span></span><br><span class="line">        <span class="comment">// 第一种，常见方式：注入自己</span></span><br><span class="line"><span class="comment">//        transactionTestService.innerMethod();</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 使用代理对象方式 ：AopContext.currentProxy()</span></span><br><span class="line"><span class="comment">//        TransactionTestService transactionTestService = (TransactionTestService) AopContext.currentProxy();</span></span><br><span class="line"><span class="comment">//        transactionTestService.innerMethod();</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 第三种方法，注入 ApplicationContext</span></span><br><span class="line"><span class="comment">//        TransactionTestService transactionTestService = (TransactionTestService) applicationContext.getBean("transactionTestService");</span></span><br><span class="line"><span class="comment">//        transactionTestService.innerMethod();</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 补充 - 获取Class: AopUtils.getTargetClass(yourObjectInstance);</span></span><br><span class="line"><span class="comment">//       AopUtils.getTargetClass(yourServiceClass);</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">protected</span> <span class="title">void</span> <span class="title">innerMethod</span>()</span>&#123;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-100 where name='用户A'"</span>);</span><br><span class="line">        System.out.println(<span class="string">"接受转账"</span>);</span><br><span class="line">        <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"转账失败"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount+100 where name='用户B'"</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>还有更多方法欢迎讨论。 </p>
<h3 id="2-抛出不被回滚的异常"><a href="#2-抛出不被回滚的异常" class="headerlink" title="2. 抛出不被回滚的异常"></a>2. 抛出不被回滚的异常</h3><p>​    这也是非常常见的情况，所以很多时候建议使用注解就加上一个<code>rollBackFor</code>，哪怕使用默认的规则也建议标记一下，因为很多时候小小的疏忽就是埋雷。</p>
<p>比如下面的方法虽然抛出异常，但是可以发现最终数据是没有回滚的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 抛出不被处理的异常</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> SQLException</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Transactional</span>(rollbackFor = RuntimeException<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">public</span> <span class="title">void</span> <span class="title">throwErrorException</span>() <span class="title">throws</span> <span class="title">SQLException</span> </span>&#123;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-100 where name='用户A'"</span>);</span><br><span class="line">        System.out.println(<span class="string">"接受转账"</span>);</span><br><span class="line">        <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> SQLException(<span class="string">"转账失败"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount+100 where name='用户B'"</span>);</span><br><span class="line">    &#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">    ========== 运行前数据准备重置数据 ========</span></span><br><span class="line"><span class="comment">    没有抛出支持回滚的异常测试</span></span><br><span class="line"><span class="comment">    接受转账</span></span><br><span class="line"><span class="comment">    ====== 运行后查询操作结果 ======</span></span><br><span class="line"><span class="comment">    &#123;id=1, name=用户A, amount=900&#125;</span></span><br><span class="line"><span class="comment">    &#123;id=2, name=用户B, amount=500&#125;</span></span><br><span class="line"><span class="comment">    </span></span><br><span class="line"><span class="comment">    */</span></span><br></pre></td></tr></table></figure>



<h3 id="3-“吞异常”"><a href="#3-“吞异常”" class="headerlink" title="3. “吞异常”"></a>3. “吞异常”</h3><p>​    吞异常也是常见的，很多时候会发现忘记抛出异常，当然实际情况没有那么明显，更多是在捕获异常之后没有抛出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 不抛出异常，导致不回滚</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">public</span> <span class="title">void</span> <span class="title">nonThrowException</span>()</span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"发起转账"</span>);</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-1100 where name='用户A'"</span>);</span><br><span class="line">        List&lt;Map&lt;String, Object&gt;&gt; maps = jdbcTemplate.queryForList(<span class="string">"select * from t_trans_test where name='用户A'"</span>);</span><br><span class="line">        Map&lt;String, Object&gt; stringObjectMap = maps.get(<span class="number">0</span>);</span><br><span class="line">        BigDecimal amount = <span class="keyword">new</span> BigDecimal(stringObjectMap.get(<span class="string">"amount"</span>).toString());</span><br><span class="line">        <span class="keyword">if</span>(amount.compareTo(BigDecimal.ZERO) &lt; <span class="number">0</span>)&#123;</span><br><span class="line">            log.error(<span class="string">"余额不支持扣款"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">    =========== 运行前数据准备重置数据 ========</span></span><br><span class="line"><span class="comment">    没有抛出异常测试</span></span><br><span class="line"><span class="comment">    发起转账</span></span><br><span class="line"><span class="comment">    : 余额不支持扣款</span></span><br><span class="line"><span class="comment">    ====== 运行后查询操作结果 ======</span></span><br><span class="line"><span class="comment">    &#123;id=1, name=用户A, amount=-100&#125;</span></span><br><span class="line"><span class="comment">    &#123;id=2, name=用户B, amount=500&#125;</span></span><br><span class="line"><span class="comment">    */</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>偷偷埋下宝藏，日后惊艳全场？更多时候建议把抓到的异常像是抓到了定时炸弹。</p>
</blockquote>
<h3 id="4-数据库引擎不支持"><a href="#4-数据库引擎不支持" class="headerlink" title="4. 数据库引擎不支持"></a>4. 数据库引擎不支持</h3><p>​    这种情况绝大多数基本不会碰到，但是如果真遇到的时候确实很难想到，这里我们可以直接把表改了之后试了一下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> t_trans_test <span class="keyword">ENGINE</span>=MyISAM;</span><br></pre></td></tr></table></figure>

<p>Mysql低版本的时候默认创建表就是用的MyISAM存储引擎，所以不要认为这种低级错误还会有人犯么？我只能说<strong>有，还不少</strong>。</p>
<p>​    修改表之后再进行前面的操作就会发现无论如何操作，最后都是没有办法回滚事务。</p>
<h3 id="5-非“公有”方法"><a href="#5-非“公有”方法" class="headerlink" title="5. 非“公有”方法"></a>5. 非“公有”方法</h3><p>​    这个相信几乎不会犯错（大概），因为如果你将一个事务注解放到一个不是public方法上，部分编辑器比如IDEA会直接提示的，比如idea提示如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Methods annotated with &#39;@Transactional&#39; must be overridable</span><br></pre></td></tr></table></figure>
<p>如果你没看到那根红线，=-=那只能自求多福了。</p>
<p>一定要注意<strong>必须是public</strong>，非要问为什么，可以问问反射和动态代理。</p>
<p>有的同学可能会说<strong>那我IDEA设置成 Protected或者默认不加任何东西，IDEA也没报错但是也没回滚呀</strong>，我只能说楼下没单杠可以去体育场……</p>
<h2 id="（3）事务传播特性实战"><a href="#（3）事务传播特性实战" class="headerlink" title="（3）事务传播特性实战"></a>（3）事务传播特性实战</h2><p>​    下面又是事务的一个重点，也是必须要掌握的一个重点，那就是关于事务隔离级别在代码中的实际使用效果，下面我们将所有的情况都试验一遍：</p>
<table>
<thead>
<tr>
<th>特点</th>
<th>传播级别</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_REQUIRED</td>
<td>如果当前存在事务，则加入该事务；如果当前没有事务，则创建一个新的事务。</td>
</tr>
<tr>
<td>支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_SUPPORTS</td>
<td>如果当前存在事务，则加入该事务；如果当前没有事务，则以非事务的方式继续运行。</td>
</tr>
<tr>
<td>支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_MANDATORY</td>
<td>如果当前存在事务，则加入该事务；如果当前没有事务，则抛出异常。（mandatory：强制性）</td>
</tr>
<tr>
<td>不支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_REQUIRES_NEW</td>
<td>创建一个新的事务，如果当前存在事务，则把当前事务挂起。</td>
</tr>
<tr>
<td>不支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_NOT_SUPPORTED</td>
<td>以非事务方式运行，如果当前存在事务，则把当前事务挂起。</td>
</tr>
<tr>
<td>不支持当前事务的情况：</td>
<td>TransactionDefinition.PROPAGATION_NEVER</td>
<td>以非事务方式运行，如果当前存在事务，则抛出异常。</td>
</tr>
<tr>
<td>其他情况</td>
<td>TransactionDefinition.PROPAGATION_NESTED</td>
<td>如果当前存在事务，则创建一个事务作为当前事务的嵌套事务来运行；如果当前没有事务，则该取值等价于TransactionDefinition.PROPAGATION_REQUIRED。</td>
</tr>
</tbody></table>
<h3 id="1-PROPAGATION-REQUIRED"><a href="#1-PROPAGATION-REQUIRED" class="headerlink" title="1. PROPAGATION_REQUIRED"></a>1. PROPAGATION_REQUIRED</h3><p>​    这个级别表示：如果当前存在事务，则加入该事务；如果当前没有事务，则创建一个新的事务。这意味如果存在嵌套的事务操作，默认会以最外层的事务的为准，这里可以验证一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1。 TransactionDefinition.PROPAGATION_REQUIRED 测试</span></span><br><span class="line"><span class="comment">     * 不同隔离级别调用</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="comment">//TransactionDefinition.PROPAGATION_REQUIRED</span></span><br><span class="line">    <span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>, <span class="title">propagation</span> </span>= Propagation.REQUIRED)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">required</span><span class="params">()</span></span>&#123;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-100 where name='用户A'"</span>);</span><br><span class="line">        transactionTestService.requiredInner();</span><br><span class="line">        <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span>  RuntimeException(<span class="string">"回滚事务"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">    =========== 运行前数据准备重置数据 ========</span></span><br><span class="line"><span class="comment">    ====== 运行后查询操作结果 ======</span></span><br><span class="line"><span class="comment">    &#123;id=1, name=用户A, amount=1000&#125;</span></span><br><span class="line"><span class="comment">    &#123;id=2, name=用户B, amount=500&#125;</span></span><br><span class="line"><span class="comment">    java.lang.RuntimeException: 回滚事务</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">		<span class="comment">// 注意这样使用会抛出异常</span></span><br><span class="line"><span class="comment">//    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.NEVER)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requiredInner</span><span class="params">()</span></span>&#123;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount+100 where name='用户B'"</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>​    从运行结果可以看出，如果在外层抛出事务的异常，哪怕内部的方法看似已经直接，最终结果依然会回滚，这也是十分常用的一种方式，所以被Spring设置这个级别为默认级别也可以理解。</p>
<h3 id="2-PROPAGATION-SUPPORTS"><a href="#2-PROPAGATION-SUPPORTS" class="headerlink" title="2. PROPAGATION_SUPPORTS"></a>2. PROPAGATION_SUPPORTS</h3><p>​    如果当前存在事务，则加入该事务；如果当前没有事务，则以非事务的方式继续运行。这种方式也好理解，就是有我就使用事务，没有我就该咋样咋样，比较随性的方式，和TransactionDefinition.PROPAGATION_REQUIRED最大区别就是在没有事务的时候不会主动创建。</p>
<p>​    这里我们来看一个比较奇怪的现象，读者可以思考一下为什么会出现下面的情况：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">     * Propagation.SUPPORTS 测试</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>, <span class="title">propagation</span> </span>= Propagation.SUPPORTS)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">required</span><span class="params">()</span></span>&#123;</span><br><span class="line">  jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-100 where name='用户A'"</span>);</span><br><span class="line">  transactionTestService.requiredInner();</span><br><span class="line">  <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span>  RuntimeException(<span class="string">"回滚事务"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">    =========== 运行前数据准备重置数据 ========</span></span><br><span class="line"><span class="comment">    ====== 运行后查询操作结果 ======</span></span><br><span class="line"><span class="comment">    &#123;id=1, name=用户A, amount=900&#125;</span></span><br><span class="line"><span class="comment">    &#123;id=2, name=用户B, amount=600&#125;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    java.lang.RuntimeException: 回滚事务</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requiredInner</span><span class="params">()</span></span>&#123;</span><br><span class="line">  jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount+100 where name='用户B'"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    从上面的代码可以看到，我们将事务的传播特性改变之后，发现无论是外部还是内部哪怕都抛出了异常，都没有进行回滚也就是说当前 的代码是没有使用事务的！！！如果我们需要让他们在同一个事务里面，可以做如下调整，下面的代码经过调整之后，在内部的事务中发现外层是存在事务的，所以他会加入到外层的事务当中，但是此时如果把外层的注解去掉，会发现它依然会非事务方式执行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> </span></span><br><span class="line"><span class="comment">     * 2。 Propagation.SUPPORTS 测试</span></span><br><span class="line"><span class="comment">     * 3。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">public</span> <span class="title">void</span> <span class="title">required</span>()</span>&#123;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-100 where name='用户A'"</span>);</span><br><span class="line">        transactionTestService.requiredInner();</span><br><span class="line">        <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span>  RuntimeException(<span class="string">"回滚事务"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">    修复之后：</span></span><br><span class="line"><span class="comment">    =========== 运行前数据准备重置数据 ========</span></span><br><span class="line"><span class="comment">    ====== 运行后查询操作结果 ======</span></span><br><span class="line"><span class="comment">    &#123;id=1, name=用户A, amount=1000&#125;</span></span><br><span class="line"><span class="comment">    &#123;id=2, name=用户B, amount=500&#125;</span></span><br><span class="line"><span class="comment">    java.lang.RuntimeException: 回滚事务</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>, <span class="title">propagation</span> </span>= Propagation.SUPPORTS)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requiredInner</span><span class="params">()</span></span>&#123;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount+100 where name='用户B'"</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>​    可以看到这个传播级别使用比较容易犯错的，所以如果有必要使用的时候一定要手动抛出异常自己测试一下。</p>
<h3 id="3-PROPAGATION-MANDATORY"><a href="#3-PROPAGATION-MANDATORY" class="headerlink" title="3. PROPAGATION_MANDATORY"></a>3. PROPAGATION_MANDATORY</h3><p>​    这个级别比较简单粗暴，意思就是必须要有失误，否则我就报错，这里我们简单修改一下上一个小节的传播级别即可看到效果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> </span></span><br><span class="line"><span class="comment">     * Propagation.SUPPORTS 测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="comment">// @Transactional(rollbackFor = Exception.class)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">required</span><span class="params">()</span></span>&#123;</span><br><span class="line">  jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-100 where name='用户A'"</span>);</span><br><span class="line">  transactionTestService.requiredInner();</span><br><span class="line">  <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span>  RuntimeException(<span class="string">"回滚事务"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">    org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line"><span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>, <span class="title">propagation</span> </span>= Propagation.MANDATORY)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requiredInner</span><span class="params">()</span></span>&#123;</span><br><span class="line">  jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount+100 where name='用户B'"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-PROPAGATION-NOT-SUPPORTED"><a href="#4-PROPAGATION-NOT-SUPPORTED" class="headerlink" title="4. PROPAGATION_NOT_SUPPORTED"></a>4. PROPAGATION_NOT_SUPPORTED</h3><p>​    创建一个新的事务，如果当前存在事务，则把当前事务挂起。这种级别设置意思是说内部的嵌套事务是独立的，如果内部存在失误则单独开启一个事务操作，但是我们实际操作之后发现居然报错了，抛出了一个CannotAcquireLockException的异常，这个异常搜索之后发现是数据库的数据行死锁了，为什么会死锁？这里建议读者可以先自己思考一下然后搜索下答案，这里就直接说了，这里涉及mysql的update机制，一个update的操作使用的是排他锁，此时按照当前的传播级别设置会出现事务挂起，但是挂起的时候锁是不会释放的，所以在内部方法执行的时候由于一直拿不到锁导致等待超时报错了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     PROPAGATION_NOT_SUPPORTED 测试</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">public</span> <span class="title">void</span> <span class="title">required</span>()</span>&#123;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-100 where name='用户A'"</span>);</span><br><span class="line">        transactionTestService.requiredInner();</span><br><span class="line">        <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span>  RuntimeException(<span class="string">"回滚事务"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">  ====== 运行后查询操作结果 ======</span></span><br><span class="line"><span class="comment">  &#123;id=1, name=用户A, amount=1000&#125;</span></span><br><span class="line"><span class="comment">  &#123;id=2, name=用户B, amount=500&#125;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    org.springframework.dao.CannotAcquireLockException: StatementCallback; SQL [update t_trans_test set amount=amount+100 where name='用户B']; Lock wait timeout exceeded; try restarting transaction; nested exception is com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>, <span class="title">propagation</span> </span>= Propagation.NOT_SUPPORTED)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requiredInner</span><span class="params">()</span></span>&#123;</span><br><span class="line">        jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount+100 where name='用户B'"</span>);</span><br><span class="line">        <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span>  RuntimeException(<span class="string">"回滚事务"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>​    这里我们通过调整事务的执行操作顺序之后，可以看到在内部的事务回滚了，但是外部的事务没有回滚，这也意味着内部的事务回滚之后外部的事务直接失效了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class"><span class="title">public</span> <span class="title">void</span> <span class="title">required</span>()</span>&#123;</span><br><span class="line">  transactionTestService.requiredInner();</span><br><span class="line">  jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount-100 where name='用户A'"</span>);</span><br><span class="line">  <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span>  RuntimeException(<span class="string">"回滚事务"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;<span class="comment">/*运行结果：</span></span><br><span class="line"><span class="comment">    =========== 运行前数据准备重置数据 ========</span></span><br><span class="line"><span class="comment">    ====== 运行后查询操作结果 =====	=</span></span><br><span class="line"><span class="comment">    &#123;id=1, name=用户A, amount=1000&#125;</span></span><br><span class="line"><span class="comment">    &#123;id=2, name=用户B, amount=600&#125;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    java.lang.RuntimeException: 回滚事务</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@Transactional</span>(rollbackFor = Exception<span class="class">.<span class="keyword">class</span>, <span class="title">propagation</span> </span>= Propagation.NOT_SUPPORTED)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requiredInner</span><span class="params">()</span></span>&#123;</span><br><span class="line">  jdbcTemplate.update(<span class="string">"update t_trans_test set amount=amount+100 where name='用户B'"</span>);</span><br><span class="line">  <span class="keyword">if</span>(EXCEPTIN_FLAG)&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span>  RuntimeException(<span class="string">"回滚事务"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-PROPAGATION-NEVER"><a href="#5-PROPAGATION-NEVER" class="headerlink" title="5. PROPAGATION_NEVER"></a>5. PROPAGATION_NEVER</h3><p>​    意思是不能有事务，有事务还会报错，这种情况就不演示了，用注解还不如不用注解，脱裤子放屁，目前个人没看到这个注解的实际使用场景。</p>
<h3 id="6-PROPAGATION-NESTED"><a href="#6-PROPAGATION-NESTED" class="headerlink" title="6. PROPAGATION_NESTED"></a>6. PROPAGATION_NESTED</h3><p>​    如果当前存在事务，则创建一个事务作为当前事务的嵌套事务来运行；如果当前没有事务，则该取值等价于<code>TransactionDefinition.PROPAGATION_REQUIRED</code>。</p>
<h1 id="七、总结"><a href="#七、总结" class="headerlink" title="七、总结"></a>七、总结</h1><p>​    这篇文章的内容比较多，Spring的事务在现在看来算是比较基础的东西，实际看代码发现并不是特别难，如果对于设计模式比较熟基本能看懂Spring的设计，下面我们来总结一下这篇文章的大致内容。</p>
<p>​    事务介绍：在文章的开始我们介绍了数据库事务的概念，事务是数据库是否流行的关键，事务的特性ACID，并发事务的问题，事务的主要四个隔离级别，以及简单介绍了事务中保存点的使用，这些是事务最为基础的内容，也是我们了解Spring事务的基础知识。</p>
<p>​    Spring事务：Spring 的事务在设计的考虑到了不同数据源以及多数据源的事务管理，在一开始我们重点列举了Spring事务的三个核心组件，将一个事务操作抽象为三个操作，获取连接，创建提交事务，回滚事务，这和上面提到的事务操作和特性和相吻合的。接着在事务隔离级别的基础上，Spring 设计了特性也就是事务的传播级别来实现不同的事务特性，在最后可以看一下整个S print设计的思路。</p>
<p>​    介绍完Spring的事务之后，开始介绍编程式事务的实现方式和声明式事务的实现方式，同时从源码的角度简单介绍了一下事务设计的核心，比如线程之间的事务隔离是通过ThreadLocal进行存储和隔离的，这也是实现嵌套事务的时候使用同一个事务的核心部分，介绍完编程式事务之后介绍了事务的核心声明式事务的，声明式的事务架构要比编程式事务复杂不少，需要更多的时间消化，并且需要一定的IOC容器和自动配置注入的知识才能看懂。</p>
<p>​    在最后的实战部分，我们总计了事务不生效的一些坑，和事务传播特性的一次实战，基本上把Spring事务注解基本使用场景列举了一下。</p>
<h1 id="写在最后"><a href="#写在最后" class="headerlink" title="写在最后"></a>写在最后</h1><p>​    主要的时间花费在阅读和理解源代码，不知道有多少人可以坚持到最后的，如果文章有任何建议或者错误欢迎指出。</p>
<h1 id="巨人的肩膀"><a href="#巨人的肩膀" class="headerlink" title="巨人的肩膀"></a>巨人的肩膀</h1><ol>
<li>如何使用原始的方式进行事务管理：<span class="exturl" data-url="aHR0cHM6Ly9jbG91ZC50ZW5jZW50LmNvbS9kZXZlbG9wZXIvYXJ0aWNsZS8xNjk3MjIx" title="https://cloud.tencent.com/developer/article/1697221">https://cloud.tencent.com/developer/article/1697221<i class="fa fa-external-link"></i></span></li>
<li><span class="exturl" data-url="aHR0cHM6Ly93d3cubWFyY29iZWhsZXIuY29tL2d1aWRlcy9zcHJpbmctdHJhbnNhY3Rpb24tbWFuYWdlbWVudC10cmFuc2FjdGlvbmFsLWluLWRlcHRo" title="https://www.marcobehler.com/guides/spring-transaction-management-transactional-in-depth">Spring Transaction Management: @Transactional In-Depth<i class="fa fa-external-link"></i></span></li>
<li><span class="exturl" data-url="aHR0cHM6Ly9zZWdtZW50ZmF1bHQuY29tL2EvMTE5MDAwMDAxODAwMTc1Mg==" title="https://segmentfault.com/a/1190000018001752">Spring源码分析：声明式事务梳理<i class="fa fa-external-link"></i></span></li>
<li><span class="exturl" data-url="aHR0cHM6Ly93d3cubWRuaWNlLmNvbS93cml0aW5nL2I0Njk2ZGNjYzljMDRjZjY4NmFlZjUwYWM4NWIzYjUw" title="https://www.mdnice.com/writing/b4696dccc9c04cf686aef50ac85b3b50">Spring声明式事务源码探究<i class="fa fa-external-link"></i></span></li>
</ol>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>lazytime
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://whitestore.top/2023/07/14/spring-total/" title="【Spring】Spring 事务机制的个人总结">https://whitestore.top/2023/07/14/spring-total/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <span class="exturl" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLzQuMC96aC1DTg=="><i class="fa fa-fw fa-creative-commons"></i>BY-NC</span> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Spring/" rel="tag"># Spring</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2023/07/11/nettychatimpl/" rel="prev" title="《跟闪电侠学Netty》阅读笔记 - 聊天系统实现">
      <i class="fa fa-chevron-left"></i> 《跟闪电侠学Netty》阅读笔记 - 聊天系统实现
    </a></div>
      <div class="post-nav-item">
    <a href="/2023/07/16/doPrivileged/" rel="next" title="【Java】关于 AccessController.doPrivileged 方法的个人理解">
      【Java】关于 AccessController.doPrivileged 方法的个人理解 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#【Spring】Spring-事务机制的个人总结"><span class="nav-number">1.</span> <span class="nav-text">【Spring】Spring 事务机制的个人总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#一、引言"><span class="nav-number">2.</span> <span class="nav-text">一、引言</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#最好的资料"><span class="nav-number">2.1.</span> <span class="nav-text">最好的资料</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二、事务介绍"><span class="nav-number">3.</span> <span class="nav-text">二、事务介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#（1）事务特性（ACID-）"><span class="nav-number">3.1.</span> <span class="nav-text">（1）事务特性（ACID ）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（2）并发事务的存在的问题"><span class="nav-number">3.2.</span> <span class="nav-text">（2）并发事务的存在的问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（3）事务的隔离级别"><span class="nav-number">3.3.</span> <span class="nav-text">（3）事务的隔离级别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（4）设置和回滚到保存点"><span class="nav-number">3.4.</span> <span class="nav-text">（4）设置和回滚到保存点</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#三、Spring事务介绍"><span class="nav-number">4.</span> <span class="nav-text">三、Spring事务介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#（1）Spring事务是啥？"><span class="nav-number">4.1.</span> <span class="nav-text">（1）Spring事务是啥？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（2）事务设计"><span class="nav-number">4.2.</span> <span class="nav-text">（2）事务设计</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（3）实现形式"><span class="nav-number">4.3.</span> <span class="nav-text">（3）实现形式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（4）事务的传播级别"><span class="nav-number">4.4.</span> <span class="nav-text">（4）事务的传播级别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（5）Spring事务和传统的区别"><span class="nav-number">4.5.</span> <span class="nav-text">（5）Spring事务和传统的区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（6）设计思路（个人理解）"><span class="nav-number">4.6.</span> <span class="nav-text">（6）设计思路（个人理解）</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#四、编程式事务"><span class="nav-number">5.</span> <span class="nav-text">四、编程式事务</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#（1）实现方式"><span class="nav-number">5.1.</span> <span class="nav-text">（1）实现方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（2）配置方式"><span class="nav-number">5.2.</span> <span class="nav-text">（2）配置方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（3）PlatformTransactionManager"><span class="nav-number">5.3.</span> <span class="nav-text">（3）PlatformTransactionManager</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#集成方式"><span class="nav-number">5.3.1.</span> <span class="nav-text">集成方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#源码解析"><span class="nav-number">5.3.2.</span> <span class="nav-text">源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（4）TransactionTemplate"><span class="nav-number">5.4.</span> <span class="nav-text">（4）TransactionTemplate</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用方式"><span class="nav-number">5.4.1.</span> <span class="nav-text">使用方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#源码解析-1"><span class="nav-number">5.4.2.</span> <span class="nav-text">源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（5）小结"><span class="nav-number">5.5.</span> <span class="nav-text">（5）小结</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#五、声明式事务"><span class="nav-number">6.</span> <span class="nav-text">五、声明式事务</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#（1）如何使用？"><span class="nav-number">6.1.</span> <span class="nav-text">（1）如何使用？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Transactional注解介绍"><span class="nav-number">6.1.1.</span> <span class="nav-text">@Transactional注解介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#监听器绑定事件"><span class="nav-number">6.1.2.</span> <span class="nav-text">监听器绑定事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JTA的集成"><span class="nav-number">6.1.3.</span> <span class="nav-text">JTA的集成</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#和-JPA-Hibernate-的集成"><span class="nav-number">6.1.4.</span> <span class="nav-text">和 JPA&#x2F;Hibernate 的集成</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#响应式事务"><span class="nav-number">6.1.5.</span> <span class="nav-text">响应式事务</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（2）配置方式-1"><span class="nav-number">6.2.</span> <span class="nav-text">（2）配置方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（3）理解事务传播级别"><span class="nav-number">6.3.</span> <span class="nav-text">（3）理解事务传播级别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（3）源码解析"><span class="nav-number">6.4.</span> <span class="nav-text">（3）源码解析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#自动配置注入"><span class="nav-number">6.4.1.</span> <span class="nav-text">自动配置注入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注解拦截解析"><span class="nav-number">6.4.2.</span> <span class="nav-text">注解拦截解析</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#六、Spring事务实战"><span class="nav-number">7.</span> <span class="nav-text">六、Spring事务实战</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#（1）介绍"><span class="nav-number">7.1.</span> <span class="nav-text">（1）介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（2）事务不生效的一些坑"><span class="nav-number">7.2.</span> <span class="nav-text">（2）事务不生效的一些坑</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-非事务方法调用事务方法"><span class="nav-number">7.2.1.</span> <span class="nav-text">1.  非事务方法调用事务方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-抛出不被回滚的异常"><span class="nav-number">7.2.2.</span> <span class="nav-text">2. 抛出不被回滚的异常</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-“吞异常”"><span class="nav-number">7.2.3.</span> <span class="nav-text">3. “吞异常”</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-数据库引擎不支持"><span class="nav-number">7.2.4.</span> <span class="nav-text">4. 数据库引擎不支持</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-非“公有”方法"><span class="nav-number">7.2.5.</span> <span class="nav-text">5. 非“公有”方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#（3）事务传播特性实战"><span class="nav-number">7.3.</span> <span class="nav-text">（3）事务传播特性实战</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-PROPAGATION-REQUIRED"><span class="nav-number">7.3.1.</span> <span class="nav-text">1. PROPAGATION_REQUIRED</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-PROPAGATION-SUPPORTS"><span class="nav-number">7.3.2.</span> <span class="nav-text">2. PROPAGATION_SUPPORTS</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-PROPAGATION-MANDATORY"><span class="nav-number">7.3.3.</span> <span class="nav-text">3. PROPAGATION_MANDATORY</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-PROPAGATION-NOT-SUPPORTED"><span class="nav-number">7.3.4.</span> <span class="nav-text">4. PROPAGATION_NOT_SUPPORTED</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-PROPAGATION-NEVER"><span class="nav-number">7.3.5.</span> <span class="nav-text">5. PROPAGATION_NEVER</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-PROPAGATION-NESTED"><span class="nav-number">7.3.6.</span> <span class="nav-text">6. PROPAGATION_NESTED</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#七、总结"><span class="nav-number">8.</span> <span class="nav-text">七、总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#写在最后"><span class="nav-number">9.</span> <span class="nav-text">写在最后</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#巨人的肩膀"><span class="nav-number">10.</span> <span class="nav-text">巨人的肩膀</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">阿东</p>
  <div class="site-description" itemprop="description">随遇而安</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">239</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">36</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">37</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2xhenlUaW1lcw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lazyTimes"><i class="fa fa-fw fa-github"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjEwOTc0ODM1MDhAcXEuY29t" title="E-Mail → mailto:1097483508@qq.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly93d3cuNTJwb2ppZS5jbi9ob21lLnBocD9tb2Q9c3BhY2UmdWlkPTE0OTc3MTgmZG89dGhyZWFkJnZpZXc9bWUmZnJvbT1zcGFjZQ==" title="https:&#x2F;&#x2F;www.52pojie.cn&#x2F;home.php?mod&#x3D;space&amp;uid&#x3D;1497718&amp;do&#x3D;thread&amp;view&#x3D;me&amp;from&#x3D;space">吾爱破解</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9qdWVqaW4uaW0vdXNlci8yOTk5MTIzNDUyNjI2MzY2" title="https:&#x2F;&#x2F;juejin.im&#x2F;user&#x2F;2999123452626366">掘金</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9zZWdtZW50ZmF1bHQuY29tL3UvbGF6eXRpbWVz" title="https:&#x2F;&#x2F;segmentfault.com&#x2F;u&#x2F;lazytimes">思否</span>
        </li>
    </ul>
  </div>

      </div>

      <div class="wechat_OA">
        <span>欢迎关注我的公众号</span>
        <br>
          <!-- 这里添加你的二维码图片 -->
        <img src ="https://adong-picture.oss-cn-shenzhen.aliyuncs.com/adong/wechat_channel.jpg">
      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">阿东</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">2m</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">29:50</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'qMUpEEvBgXaMDD1b0ftgi9xr-gzGzoHsz',
      appKey     : 'UCdfT4Rfih6MO6y8DI4fstf6',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
